5-Reducers
2020-01-29 本文已影响0人
钢笔先生
Time: 20200129
Reducers
Specify how the app's state changes in response to actions sent to the store.
简单来说,Reducers是纯函数,接收state和action作为参数,返回新的状态。即:
(previousState, action) => newState
初始状态会传递给reducer
,如同我们在useReducer Hook
中做的那样。
// 定义一个reducer
const reducer = (state=initialState, action) => {
switch (action.type) {
case BUY_CAKE:
return {
...state,
numOfCakes: state.numOfCakes - 1
}
default:
return state
}
}
根据约定,action
会有一个type
字段,用于描述是哪个动作类型,然后针对不同的动作返回不同的新状态,默认是返回原状态。
会有一个问题是,当前状态是如何传递到reducer
的?
另外,状态通常不止一个属性,而我们带来的action
通常不会是全部的状态,而是部分属性的修改,因此用...
操作符复制一份原数据,然后再修改部分数据。
END.