【发布时间】:2021-12-18 09:17:22
【问题描述】:
我正在尝试为 RTK 编写一个切片,但我不确定我的有效载荷应该是什么类型。我的状态 -- InviteeState 是一个人员对象数组
interface InviteeState {
people: {
name: string,
age: number,
url: string,
note?: string
}[]
}
然后我设置我的initialState
const initialState: InviteeState = {
people: [],
}
在我的切片中:
export const inviteesSlice = createSlice({
name: "invitees",
initialState,
reducers: {
// method to update state
addInvitee: (state, action: PayloadAction<"people"[]>) => {
state.people.push(action.payload)
}
}
})
但在state.people.push(action.payload) 行中,action.payload 抛出错误
“类型 '"people"[]' 缺少类型 'WritableDraft': name, age,网址”
我不确定我的PayloadAction<"people"[]> 类型是否错误,或者我的inistialState 是否也错误。
我怎么知道正确的类型应该是什么?
【问题讨论】:
-
应该是
{name: string,age: number,url: string,note?: string} -
有没有办法将它设置为变量,这样我就不必输入每个属性?我认为这就是 state var 的用途。谢谢。
-
是的,你应该把你的interface改成type,那么PayloadAction的type就是
InviteeState["people"][number]
标签: reactjs typescript redux redux-toolkit