React Redux报错:传递给Reducer的state未定义,需显式返回初始状态
React Redux报错解决:If the state passed to the reducer is undefined,you must explicitly return the initial state
问题描述
我是React Redux新手,遇到如下错误:
If the state passed to the reducer is undefined,you must explicitly return the initial state
store.js 代码
import { applyMiddleware, combineReducers, createStore } from "redux" import thunk from "redux-thunk" import {composeWithDevTools} from "redux-devtools-extension" import authReducer from "./reducers/auth" const initialState = { } const reducers = combineReducers({ auth: authReducer }) const store = createStore(reducers,initialState, composeWithDevTools(applyMiddleware(thunk))) export default store
auth reducer 代码
const authReducer = (state = {auth:null}, action) =>{ switch (action.type) { case "REGISTER": localStorage.setItem('auth',JSON.stringify(action.payload)) return{ ...state, auth:action.payload } case "LOGIN": localStorage.setItem('auth',JSON.stringify(action.payload)) return{ ...state, auth: action.payload } case "LOGUT": localStorage.clear() return{ ...state, auth: null } default: break; } } export default authReducer
我原本想获取登录表单的数据,但出现了上述错误。
解决方法
错误根源是authReducer的default分支仅执行了break,没有返回任何值。当Redux初始化或遇到未匹配的action类型时,reducer返回undefined,触发该报错。
修改authReducer的default分支,直接返回当前state即可:
const authReducer = (state = {auth:null}, action) =>{ switch (action.type) { case "REGISTER": localStorage.setItem('auth',JSON.stringify(action.payload)) return{ ...state, auth:action.payload } case "LOGIN": localStorage.setItem('auth',JSON.stringify(action.payload)) return{ ...state, auth: action.payload } case "LOGUT": localStorage.clear() return{ ...state, auth: null } default: // 必须返回当前state,不能仅break return state; } } export default authReducer
额外提示
- 注意到你写的
LOGUT是拼写错误,正确应为LOGOUT,后续调用action时要对应修改,避免触发default分支 - 你在store中定义的
initialState是空对象,但reducer已经通过默认参数state = {auth:null}设置了初始状态,这部分没问题;如果想统一管理初始化状态,也可以把store的initialState改为{ auth: { auth: null } },非强制要求。
内容的提问来源于stack exchange,提问作者HuseyinKan
相关产品推荐
相关产品推荐

