gpt4 book ai didi

javascript - 为什么我的 Redux reducer 重构失败了?

转载 作者:行者123 更新时间:2023-11-30 11:26:26 25 4
gpt4 key购买 nike

这是我正在尝试做的一个例子:

const setView = state => payload => ({ ...state, view: payload });

const reducers = {
SET_VIEW: setView
};

export default (state = initialState, action) => reducers[action.type](state)(action.payload);

不幸的是,我收到以下错误:

Uncaught TypeError: reducers[action.type] is not a function

我究竟做错了什么? reducers 是一个带有函数的对象字面量。

最佳答案

这其实是一个很晦涩的问题。原因是因为,根据 the Redux documentation on createStore :

When a store is created, Redux dispatches a dummy action to your reducer to populate the store with the initial state. You are not meant to handle the dummy action directly. Just remember that your reducer should return some kind of initial state if the state given to it as the first argument is undefined, and you're all set.

文档中提到的这个虚拟操作恰好发生在 be this line the source 上。 :

dispatch({ type: ActionTypes.INIT })

这里,ActionTypes.INIT 本质上是字符串 @@redux/INIT 后跟随机的数字和句点字符串。

因此,当您使用 createStore 创建商店时,会将一个虚拟操作分派(dispatch)给您的 reducer,并且您的 reducers 对象中不存在该操作类型,因此您会得到未定义不是函数的错误。这就是为什么您总是在您的 reducer 中有一个 default case 的原因。例如,对于 switch 语句,您始终将状态作为默认情况返回:

switch(action.type) {

default:
return state;
}

默认情况允许捕获 Action ,例如 Redux 本身调度的虚拟 Action 。同样的原则适用于您的代码:

export default (state = initialState, action) => reducers[action.type] ? reducers[action.type](state)(action.payload) : state;

这会检查 reducer 是否确实存在于 reducers 对象中。如果是,它会调用 reducer 。如果不是,就像在默认情况下一样,只返回状态。

关于javascript - 为什么我的 Redux reducer 重构失败了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47862672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com