[英]Redux toolkit typescript -- what is my PayloadAction type?
I'm trying to write a slice for RTK and I'm not sure what the type of my payload should be.我正在尝试为 RTK 编写一个切片,但我不确定我的有效负载的类型应该是什么。 My state -- InviteeState
is an array of people objects我的状态InviteeState
是一组人员对象
interface InviteeState {
people: {
name: string,
age: number,
url: string,
note?: string
}[]
}
Then I'm setting my initialState
然后我设置我的initialState
const initialState: InviteeState = {
people: [],
}
And in my slice:在我的切片中:
export const inviteesSlice = createSlice({
name: "invitees",
initialState,
reducers: {
// method to update state
addInvitee: (state, action: PayloadAction<"people"[]>) => {
state.people.push(action.payload)
}
}
})
But In the state.people.push(action.payload)
line the action.payload
is throwing the error但是在state.people.push(action.payload)
行中action.payload
抛出错误
"Type '"people"[]' is missing the following properties from type 'WritableDraft<{ name: string; age: number; url: string; note?: string | undefined; }>': name, age, url" “类型 '”people”[]' 缺少类型 'WritableDraft<{ name: string; age: number; url: string; note?: string | undefined; }>': name, age, url 中的以下属性”
I'm not sure if my PayloadAction<"people"[]>
type is wrong or if my inistialState
is wrong also.我不确定我的PayloadAction<"people"[]>
类型是否错误,或者我的inistialState
是否也错误。
How do I know what the correct type should be?我怎么知道正确的类型应该是什么?
Your payloadAction should be person object.您的 payloadAction 应该是 person 对象。
First declare the type for "people":首先声明“people”的类型:
interface Person {
// properties
}
interface InviteeState {
people: Person[]
}
Then the initial state would be:那么初始状态将是:
const initialState: InviteeState = {
people: Person[] = [],
}
You can use Person
in your slice:您可以在切片中使用Person
:
export const inviteesSlice = createSlice({
name: "invitees",
initialState,
reducers: {
// adding Person to state tree
addInvitee: (state, action: PayloadAction<Person>) => {
state.people.push(action.payload)
}
}
})
You can call that action like:您可以调用该操作,例如:
let person:Person // of course with actual data in this
dispatch(
addInvitee(people)
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.