reactjs - 为什么我的减速器返回未定义的 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。
解决方案
您唯一需要做的就是始终从 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;
};
您需要遵循的一些规则:
- 总是需要返回状态,即使你没有改变任何东西,即使值只是
null
. - 你不应该有 return
undefined
。 - 如果状态发生变化,则需要替换它,例如:
{...state, newValue: false}
.
从文档:
我们在默认情况下返回之前的状态。对于任何未知操作,返回之前的状态很重要。
进一步阅读:处理动作
我希望这有帮助!
推荐阅读
- javascript - Map 和 FlatMap 抛出错误“Typescript 中的类型‘未知’上不存在属性‘地图’
- aspnetboilerplate - 在使用自定义 AppService 的 AspNet Boilerplate DotNetCore 控制台应用程序中,它不执行依赖注入
- android - Android Room - 自定义查询以根据条件返回特定值
- python - UnicodeDecodeError 使用 Windows 命令提示符打开 python 文件
- github - 文件夹/文件未更新到 Github?
- python - 从不同目录访问 Python 模块
- typescript - TS4090 错误:电子中节点的库冲突
- qt - 如何使 windeployqt 仅包含所需的模块?
- ruby-on-rails - 如何从孩子访问父数据
- linux - 使用 git 计算可合并提交的数量