简体   繁体   English

如何使用 Typescript 将多个参数传递给 redux 减速器?

[英]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.我正在尝试使用 useDispatch 将多个参数传递给 RTK 减速器。 Typically I would wrap the parameters in an object or array and destructure in the reducer.通常我会将参数包装在 object 或数组中,然后在减速器中解构。 But I'm having a tough time doing this with Typescript, other than using my famous cheat code "any".但是我很难用 Typescript 做这件事,除了使用我著名的作弊码“任何”。 I feel this is an extremely ignorant question and showcases my newness to Typescript, but would appreciate any help!我觉得这是一个非常无知的问题,并展示了我对 Typescript 的新鲜感,但如果有任何帮助,我将不胜感激!

types:类型:

  • marker.id = string标记.id = 字符串
  • e.nativeEvent.coordinate = {latitude: number, longitude: number} e.nativeEvent.coordinate = {纬度:数字,经度:数字}

dispatch in my map component:在我的 map 组件中调度:

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

rtk slice: rtk 切片:

    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.使用 Redux Toolkit,生成的动作创建者默认只接受一个参数。 If you want to pass in multiple values, you need to do so as an object.如果要传入多个值,则需要以 object 的形式进行。 And, the generic you provide to PayloadAction should define the fields and types in that object, such as:而且,您提供给PayloadAction的泛型应该定义该 object 中的字段和类型,例如:

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:如果您真的想将它们作为单独的参数传递,您可以编写一个“准备回调”,自己将它们转换为单个payload字段:

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.但大多数时候不值得。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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