redux 错误:在初始化过程中,减速器“计数器”返回未定义,如果传递给减速器的状态未定义

1bqhqjot  于 2023-02-04  发布在  其他
关注(0)|答案(3)|浏览(100)

我试图做reduxer(学习)的基本测试,它似乎基本没有问题,但我得到这个错误”×错误:在初始化期间,Reducer“counter”返回未定义的值。如果传递给Reducer的状态未定义,则必须显式返回初始状态。初始状态可能未定义。如果不想为此Reducer设置值,则可以使用null而不是undefined。
我相信回应是非常愚蠢的希望得到帮助。
Reduxer文件. counter.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;

索引. 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();
d7v8vwbk

d7v8vwbk1#

默认情况下应从reducer返回

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

每一个reducer接收每一个动作的分派。如果你不知道动作的类型,你应该原封不动地返回状态。

wvyml7n5

wvyml7n52#

const counterReducer = (state = 0, action) => {
  switch (action.type) {
    case "INCREMENT":
      return state + 1
    case "DECREMENT":
      return state - 1
    default:
      return state // Don't ever forget to add a Default case.
  }
}

💡永远不要忘记添加一个默认情况...,因为如果传递给reducer的状态是未定义的。

cs7cruho

cs7cruho3#

为每个reducer返回一个默认的case。一般来说,你应该总是为switch语句提供默认的case。如果你不这样做,你可能会遇到意想不到的问题。此外,它可以使调试变得容易得多,因为你知道你已经通过了所有的case,而不必猜测。

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

相关问题