错误:在初始化期间,reducer“计数器”返回未定义。如果传递给减速器的状态未定义

时间:2020-08-10 14:24:18

标签: redux react-redux

我正在尝试对reduxer(Learning)进行基本测试,看来基本没问题,但出现此错误”× 错误:在初始化期间,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;
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();

2 个答案:

答案 0 :(得分:1)

默认情况下,您应该从reducer返回

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

每个reducer都会收到每个动作分派。如果您不知道该操作,则应返回原状。

答案 1 :(得分:0)

 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的状态是未定义的。