5-Reducers

作者: 钢笔先生 | 来源:发表于2020-01-29 14:50 被阅读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.

相关文章

  • 5-Reducers

    Time: 20200129 Reducers Specify how the app's state chang...

网友评论

    本文标题:5-Reducers

    本文链接:https://www.haomeiwen.com/subject/ylgvthtx.html