gpt4 book ai didi

redux - 错误 : Reducer "counter" returned undefined during initialization. 如果传递给 reducer 的状态未定义

转载 作者:行者123 更新时间:2023-12-01 23:52:11 24 4
gpt4 key购买 nike

我正在尝试对 reduxer(Learning) 进行基本测试,它看起来很基本,没有问题,但我得到了这个错误"×错误: reducer “计数器”在初始化期间返回未定义。如果传递给 reducer 的状态未定义,则必须显式返回初始状态。初始状态可能不是未定义的。如果你不想为这个 reducer 设置一个值,你可以使用 null 而不是 undefined。”

我认为这种回应是非常愚蠢的希望得到帮助。

Reduxer 文件。计数器.js

const counterReducer = (state = 0, action) => {
switch (action.type) {
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1;
}
};

export default counterReducer;

isLogged.js

const loggedReducer = (state = false, action) => {
switch (action.type) {
case "SING_IN":
return !state;
default:
return state;
}
};
export default loggedReducer;
index.js

import counterReducer from "./counter";
import loggedReducer from "./isLogged";
import { combineReducers } from "redux";

const allReducers = combineReducers({
counter: counterReducer,
isLogged: loggedReducer,
});

export default allReducers;

src 文件夹>index.js.

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from "./serviceWorker";
import { createStore } from "redux";
import allReducer from "./reducers";

const store = createStore(
allReducer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);

ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById("root")
);


serviceWorker.unregister();

最佳答案

你应该默认从reducer返回

const counterReducer = (state = 0, action) => {
switch (action.type) {
case "INCREMENT":
return state + 1;
case "DECREMENT":
return state - 1;
default:
return state;
}
};

每个 reducer 都会收到分派(dispatch)的每个 action。如果您不知道操作类型,您应该返回原样的状态。

关于redux - 错误 : Reducer "counter" returned undefined during initialization. 如果传递给 reducer 的状态未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63342121/

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