Redux 工具包打字稿——我的 PayloadAction 类型是什么?

Redux toolkit typescript -- what is my PayloadAction type?

我正在尝试为 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 抛出错误

“类型“人”[]”缺少类型 'WritableDraft<{ name: string; age: number; url: string; note?: string | undefined; }>' 中的以下属性:姓名、年龄、url“

我不确定我的 PayloadAction<"people"[]> 类型是否有误,或者我的 inistialState 是否也有误。

我怎么知道正确的类型应该是什么?

你的 payloadAction 应该是 person 对象。

首先声明“people”的类型:

interface Person {
    // properties
}

interface InviteeState {
  people: Person[]
}

那么初始状态为:

const initialState: InviteeState = {
  people: Person[] = [], 
}

您可以在切片中使用 Person

export const inviteesSlice = createSlice({
  name: "invitees",
  initialState,
  reducers: {
    // adding Person to state tree
    addInvitee: (state, action: PayloadAction<Person>) => {
        state.people.push(action.payload)
    }
  }
})

您可以像这样调用该操作:

let person:Person // of course with actual data in this

dispatch(
    addInvitee(people)
)