gpt4 book ai didi

javascript - 在redux中使用combineReducers时如何修复shape AssertionError?

转载 作者:行者123 更新时间:2023-12-03 02:20:10 27 4
gpt4 key购买 nike

我在redux (redux@3.7.2) 中使用combineReducer 方法时遇到错误。当我只使用一个 reducer 时,相同的代码将起作用。

Running code here

代码

const { createStore, combineReducers, applyMiddleware } = require ('redux')

const aReducer = (state, action) => {
switch (action.type) {
case 'A':
{
return { ...state };
}
default: return state;
}
return state;
}

const bReducer = (state, action) => {
switch (action.type) {
case 'B':
{
return { ...state };
}
default: return state;
}
return state;
}

const configureStore = (initialState) => {


let rootReducer = combineReducers({ a:aReducer, b:bReducer });
console.log('configureStore', initialState);
const str = createStore(rootReducer, initialState);
return str;
};


const store = configureStore({});

console.log('store',store);

store.subscribe(() => {

console.log(store.getState());

});

在创建存储行中,如果我将 rootReducer 替换为 aReducer,则此代码不会有任何问题。我不明白为什么 reducer 返回未定义的状态,我将初始状态作为平面对象传递。

最佳答案

这里发生了两件事。首先combineReducers还将对象中每个 reducer 的状态与参数 reducer 对象相同的键组合在一起,因此要正确初始化每个状态,您需要:

const store = configureStore({a: {}, b: {}});

但这还不足以解决问题,如 combineReducers还要求每个reducer能够处理状态undefined并且永远不会返回undefined(see the docs)。如果不能,您会收到此错误:

Error: Reducer "..." returned undefined during initialization. If the state passed to the
reducer is undefined, you must explicitly return the initial state. The initial state may
not be undefined. If you don't want to set a value for this reducer, you can use null
instead of undefined.

令人困惑的是,检查是在 combineReducers 时完成的。被调用(即在状态初始化之前),但直到使用 reducer 后才会显示错误。这意味着即使您正确初始化状态,您的 reducer 也永远不会收到状态 undefined ,如果 reducer 无法处理它,您仍然会收到错误。

要修复它,请替换 (state, action) => {在每个 reducer 中 (state = {}, action) => { ,或显式返回 null如果stateundefined 。请注意,仅当您不将初始状态传递给 createStore 时,才会使用这些初始状态。 。为了防止混淆,我通常在 reducer 中进行所有初始化,而不是在 createStore 处进行。 .

关于javascript - 在redux中使用combineReducers时如何修复shape AssertionError?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49193305/

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