复杂以后 setState 就不太方便了
所以使用Redux来管理 React只负责View。
Store、State、Dispatch、Reducer
reducer(state,action)
{
switch(action.type){
case ...
... ...
return newAction;
}
}
·通过Reducer创建Store
·Store.dispatch(action)来修改状态
·Reducer函数接受state和action,返回新的state,可用store.subscribe监听每次修改
function listener() {
const current = store.getState()
console.log(current);
}
store.subscribe(listener)
store.dispatch({ type: '...' })
store.dispatch({ type: '...' })
二、Redux配合React使用
index.js:
const store = createStore(reducer)
<App store={store}/>
App.js:
render(){
const num = this.props.store
return({num})
}
三、Redux处理异步