(TS - Redux) 如何将状态 属性 初始化为 null:类型 'UserData' 不可分配给类型 'null'
(TS - Redux) How to initialize state property as null: Type 'UserData' is not assignable to type 'null'
我遇到此错误:类型 'UserData' 无法分配给类型 'null'。
我将用户状态 属性 定义为 user: UserData | null;... 所以我不明白为什么它不允许我将 属性 初始化为 null 然后为它分配一个类似 UserData 的值:
Error Console
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了解更多信息
我遇到此错误:类型 'UserData' 无法分配给类型 'null'。
我将用户状态 属性 定义为 user: UserData | null;... 所以我不明白为什么它不允许我将 属性 初始化为 null 然后为它分配一个类似 UserData 的值: Error Console
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了解更多信息