首页 > 解决方案 > 为什么我的减速器返回未定义的 React TypeScript

问题描述

我正在尝试Redux使用 React 设置我的商店,TypeScript但它给了我一个错误,我的auth减速器是undefined.

这是我的store.ts

import {Action, applyMiddleware, combineReducers, compose, createStore} from 'redux';
import { auth, IAuthState } from './Auth/reducer';
import { general, IGeneralState } from './General/reducer';

export interface IAppState {
    auth: IAuthState;
    general: IGeneralState;
}

export const rootReducer = () => combineReducers({
        auth: auth,
        general: general,
});

const store = createStore<IAppState, Action<any>, {}, {}>(
    rootReducer(),
    (window as any).__REDUX_DEVTOOLS_EXTENSION__ &&
    (window as any).__REDUX_DEVTOOLS_EXTENSION__()
);

export { store };

这是我的auth reducer

import { User } from '../../interfaces/user.interface';
import { AuthActionTypes } from './actions';

export interface IAuthState {
    user: User;
    authenticated: boolean;
}

const initialState: IAuthState = {
    user: null,
    authenticated: true,
};

export const auth = (state: IAuthState = initialState, action: any): IAuthState => {
    switch (action.type) {
        case AuthActionTypes.Setuser:
            const { User } = action.payload;

            return {
                ...state,
                user: User
            };

        case AuthActionTypes.Logout:

            return {
                ...state,
                user: null,
                authenticated: false,
            };
    }
};

它给了我错误:

未捕获的错误:Reducer “auth”在初始化期间返回未定义。如果传递给 reducer 的状态未定义,则必须显式返回初始状态。初始状态可能不是未定义的。如果你不想为这个 reducer 设置值,你可以使用 null 而不是 undefined。

标签: reactjstypescriptredux

解决方案


您唯一需要做的就是始终从 reducer 返回一个值,即使它是null.

以下修复将完成这项工作:

export const auth = (state: IAuthState = initialState, action: any): IAuthState => {
    switch (action.type) {
        case AuthActionTypes.Setuser:
            const { User } = action.payload;

            return {
                ...state,
                user: User
            };

        case AuthActionTypes.Logout:

            return {
                ...state,
                user: null,
                authenticated: false,
            };
    }

    // this step was missing
    return state;
};

您需要遵循的一些规则:

  1. 总是需要返回状态,即使你没有改变任何东西,即使值只是null.
  2. 你不应该有 return undefined
  3. 如果状态发生变化,则需要替换它,例如:{...state, newValue: false}.

从文档:

我们在默认情况下返回之前的状态。对于任何未知操作,返回之前的状态很重要。

进一步阅读:处理动作

我希望这有帮助!


推荐阅读