10分钟理解 redux
本章的主要内容React数据传递、redux和React-redux等等。

第一节 react数据传递
react 中组件之间数据传递
1. 父传子

2. 子传父(状态提升)

3. 兄弟之间传递
需要把数据上传到共有的父级身上,然后再通过父级向下传,传到指定的子级上
本节作业
兄弟元素之间数据传递
两个具有共同祖先级的元素之间数据传递
第二节 redux
1. 介绍:
Redux 是 JavaScript 状态容器,提供可预测化的状态管理。Redux 由 Flux 演变而来,但受 Elm 的启发,避开了 Flux 的复杂性。redux能统一管理数据,只要redux中的数据发生改变了,所有使用redux中数据的地方都会改变。redux有自己的一套操作标准。
2. 使用
1. 安装:
npm install --save redux
使用react时安装:
npm install --save react-redux
npm install --save-dev redux-devtools
2. 三大原则
1.单一数据源
整个应用的 state 被储存在一棵 object tree 中,并且这个 object tree 只存在于唯一一个 store 中。
2.使用纯函数来执行修改
如何改变 state tree ,你需要编写 reducers。它接收先前的 state 和 action,并返回新的 state
3.State 是只读的
唯一改变 state 的方法就是触发 action,action 是一个用于描述已发生事件的普通对象。
执行上面纯函数。
3. 核心
1. Action
function gaiTel(){
return {
type:'GAITEL' , // 要办业务类型
data:'12345678911' , // 新数据
}
}
2. Reducer
业务流程:

3. Store
1. 调用业务流程,执行
store.dispatch(Action)
2. 创建出来唯一的仓库
let store = createStore(Reducer)
4. 基本使用:
见:redux1.js
本节作业:
理解redux核心
创建一个redux数据
第三节react-redux
1. 安装:
npm install --save redux
npm install --save react-redux
npm install --save-dev redux-devtools
Redux-devtools 使用网址:
https://github.com/zalmoxisus/redux-devtools-extension#installation
2. 使用
1. redux 核心代码都不变
2. 连接react
1. 关联整个react项目 index.js

2. 某个组件关联store

3. 页面中进行读写操作
不管是读还是写,都是通过 this.props
4. redux中数据改变了,但是页面不更新
原因:state 是只读的,不能改变它,改变后页面也不会更新
解决方法:生成一个新的state
1.使用 {...state}
2. let newobj ={}
Object.assign(newobj,state)
本节作业:
页面中使用redux数据
页面中修改redux中的数据
第四节 其他
1. reducers合并

2. 异步action
1. 下载中间件
npm i --save redux-thunk
2. 配置:
在createStore是配置
import thunkMiddleware from 'redux-thunk'
import { createStore, applyMiddleware } from 'redux'
const store = createStore(rootReducer,applyMiddleware(
thunkMiddleware // 允许我们 dispatch() 函数
)
3.在action中异步请求数据

组件中调用 asyncSetChat
componentDidMount(){
this.props.chatActions.asyncSetChat("http://iwenwiki.com/api/blueberrypai/getIndexChating.php")
}
本节作业:
练习异步操作action