将 React Redux Toolkit 与 Typescript 结合使用 - 为 reducer 设置状态
Using React Redux Toolkit with Typescript - set state for reducer
我正在尝试将 React Redux Toolkit 与 TypeScript 结合使用,但在为用户模型创建缩减程序时遇到了这个问题。
这是我的 userReducer.ts 文件:
import { createReducer } from "@reduxjs/toolkit";
import { UserModel } from "../../models/UserModel";
import {setUser, getUser, removeUser} from "../actions/userActions";
const initialState: UserModel = {
email: "",
id: "",
}
export const userReducer = createReducer(initialState, (builder) =>
builder
.addCase(getUser, (state) => state)
.addCase(removeUser, () => initialState)
.addCase(setUser, (state, action) => { ...state, ...action.payload })
);
我在设置用户的最后一个 addCase 上遇到问题,intellisense 说:
A spread argument must either have a tuple type or be passed to a rest parameter.ts(2556)
Cannot find name 'state'.ts(2304)
我不明白如何修复它,更具体地说,我不明白如何使用带有 Typescript 的 Redux 正确设置状态。
我想你想 return 状态更新为 action.payload?:
.addCase(setUser, (state, action) => ({ ...state, ...action.payload }))
我正在尝试将 React Redux Toolkit 与 TypeScript 结合使用,但在为用户模型创建缩减程序时遇到了这个问题。
这是我的 userReducer.ts 文件:
import { createReducer } from "@reduxjs/toolkit";
import { UserModel } from "../../models/UserModel";
import {setUser, getUser, removeUser} from "../actions/userActions";
const initialState: UserModel = {
email: "",
id: "",
}
export const userReducer = createReducer(initialState, (builder) =>
builder
.addCase(getUser, (state) => state)
.addCase(removeUser, () => initialState)
.addCase(setUser, (state, action) => { ...state, ...action.payload })
);
我在设置用户的最后一个 addCase 上遇到问题,intellisense 说:
A spread argument must either have a tuple type or be passed to a rest parameter.ts(2556)
Cannot find name 'state'.ts(2304)
我不明白如何修复它,更具体地说,我不明白如何使用带有 Typescript 的 Redux 正确设置状态。
我想你想 return 状态更新为 action.payload?:
.addCase(setUser, (state, action) => ({ ...state, ...action.payload }))