React ---- 状态管理之Redux
REDUX: 状态管理
flux ->
|- vuex // vue
|- react-redux // react
下面说一下具体实现
第一步:在组件外部定义 store
1.创建默认状态(一般const or let一个对象)
2.创建 reducer 纯函数(函数必须有返回值)
let reducer=(state=defaultState,action)=>{
let {type,payload}=action;
switch (type){
case ADD_ITEM:
// state.arr.push(payload) //直接修改state
return Object.assign({},state,{
arr: state.arr.concat(payload)
});
break;
default:
return state;
}
};
3.实例化 store 对象
let store = createStore(reducer,defaultState);
第二步:在组件里面使用 store
1.订阅 store (一般在 componentDidMount 里来接受 store 数据)
this.props.store.subscribe(()=>{ //订阅store的状态
console.log(收到订阅了store的数据);
console.log(this.props.store.getState()); //state对象
this.setState({
arr:this.props.store.getState().arr
});
})
2.action(发布/更新)数据(一般为事件触发函数)
this.props.store.dispatch({
type:ADD_ITEM,
payload:this.refs.t1.value
});
