简体   繁体   中英

How can I pass multiple parameters to a redux reducer with Typescript?

I'm trying to pass multiple parameters to a RTK reducer using useDispatch. Typically I would wrap the parameters in an object or array and destructure in the reducer. But I'm having a tough time doing this with Typescript, other than using my famous cheat code "any". I feel this is an extremely ignorant question and showcases my newness to Typescript, but would appreciate any help!

types:

  • marker.id = string
  • e.nativeEvent.coordinate = {latitude: number, longitude: number}

dispatch in my map component:

dispatch(updateMarkerCoords([marker.id, e.nativeEvent.coordinate]))

rtk slice:

    updateMarkerCoords: (state, action: PayloadAction<Array<any>>) => {
      const [id, coords] = action.payload
      const marker = state.addNewField.markers.find((m) => m.id === id)
      if (marker) {
        marker.coords = coords
      }
    },

With Redux Toolkit, generated action creators only accept one argument by default. If you want to pass in multiple values, you need to do so as an object. And, the generic you provide to PayloadAction should define the fields and types in that object, such as:

updateMarkerCoords(state, action: PayloadAction<{id: string, coordinate: number}>) {
  // use action.payload.id and action.payload.coordinate here
}

If you really want to pass them in as separate parameters, you can write a "prepare callback" that converts them into the single payload field yourself:

updateMarkerCoordinate: {
  reducer(state, action: PayloadAction<{id: string, coordinate: number}>) {
    // same logic here
  },
  prepare(id: string, coordinate: number) {
    return {payload: {id, coordinate}}
  }
}

but most of the time it isn't worth it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM