(TS - Redux)如何将状态属性初始化为 null:类型 'UserData' 不可分配给类型 'null'



我遇到以下错误:类型"UserData"不可分配给类型"null">

我将用户状态属性定义为user:UserData|null。。。所以我不明白为什么它不允许我将属性初始化为null,然后为它分配一个类似UserData的值:错误控制台

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { UserData } from "../../types/user";
interface AppState {
user: UserData | null;
}
const appSlice = createSlice({
name: 'app',
initialState: { user: null },
reducers: {
loadUserIntoApp: {
reducer(state, action: PayloadAction<UserData>) {
state.user = action.payload; // This is the line with an error
}
}
}
})

您应该将AppState接口推断为initialState

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { UserData } from "../../types/user";
interface AppState {
user: UserData | null;
}
const appSlice = createSlice({
name: 'app',
initialState: AppState = { user: null },
reducers: {
loadUserIntoApp: {
(state, action: PayloadAction<UserData>) => { //you should add the reducer like this
state.user = action.payload;
}
}
}
})

转到decumetation了解更多信息

相关内容

  • 没有找到相关文章

最新更新