Reducer
一个纯函数,接收旧的state和action返回新的state 永远不要执行以下操作:
- 修改传入参数
- 执行副作用操作,如:API请求,路由跳转
- 调用非纯函数,如:Math.floot
(previousState,action) => newState
使用
index
import { createStore } from "redux";
//创建sotre,reducer传进去
const store = createStore((state = 0, action) => {
switch (action.type) {
case "ADD":
return state + 1;
case "MINUS":
return state - 1;
default:
return state;
}
});
export default store
读取
<p>{store.getState()}</p>
修改
addClick = () => {
store.dispatch({type:"ADD"})
}
订阅和取消订阅
componentDidMount(){
//告诉redux,一旦state变化执行subscribe
this.unSubscribe = store.subscribe(() => {this.forceUpdate()})
}
componentWillUnmount(){
this.unSubscribe()
}