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

jjr*_*ise 2 javascript reactjs redux react-redux redux-toolkit

我正在尝试使用 useDispatch 将多个参数传递给 RTK 减速器。通常,我会将参数包装在对象或数组中,并在化简器中进行解构。但除了使用我著名的作弊代码“any”之外,我在使用 Typescript 时遇到了困难。我觉得这是一个非常无知的问题,并展示了我对 Typescript 的陌生,但希望得到任何帮助!

类型:

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

在我的地图组件中调度:

dispatch(updateMarkerCoords([marker.id, e.nativeEvent.coordinate]))
Run Code Online (Sandbox Code Playgroud)

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
      }
    },
Run Code Online (Sandbox Code Playgroud)

mar*_*son 5

使用 Redux Toolkit,生成的操作创建者默认只接受一个参数。如果您想传入多个值,则需要将其作为对象来执行。并且,您提供的泛型PayloadAction应该定义该对象中的字段和类型,例如:

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

如果您确实想将它们作为单独的参数传递,您可以编写一个“准备回调”,payload自行将它们转换为单个字段:

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

但大多数时候这是不值得的。