深入浅出Redux系列

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.

上一篇 下一篇

猜你喜欢

热点阅读