React 键“mods”的切片缩减器在初始化期间返回未定义。(还原)

Lun*_*Lun 3 reactjs redux react-redux

减速器/index.js

import { combineReducers } from "redux";
import mods from "./mods.js";

export default combineReducers({ // <----- error comes from here
    mods
})
Run Code Online (Sandbox Code Playgroud)

减速器/mods.js

import { GET_MODS } from "../actions/types"

const initialState = {
    mods: [],
}

export default function(state = initialState, action) {
    switch(action.type) {
        case GET_MODS:
            return {
                ...state,
                mods: action.payload
            }
    }
}
Run Code Online (Sandbox Code Playgroud)

不知道为什么会发生这种情况,我做过类似的事情,但从未遇到过这个问题,我是 redux 新手,所以这可能是一个愚蠢的错误......

// 错误

错误:关键“mods”的切片缩减器在初始化期间返回未定义。如果传递给reducer的状态未定义,则必须显式返回初始状态。初始状态可能不是未定义的。如果您不想为此减速器设置值,可以使用 null 而不是 undefined。

小智 9

尝试添加默认情况,

export default function (state = initialState, action) {
  switch (action.type) {
    case GET_MODS:
      return {
        ...state,
        mods: action.payload
      }
    default:
      return state
  }
}
Run Code Online (Sandbox Code Playgroud)