Redux-toolkit payload don't reconigze type

siv3szwd  于 2023-11-19  发布在  其他
关注(0)|答案(3)|浏览(89)

我在我的项目中使用redux-toolkit,我遇到了这个问题
我创建了这个reducer:

setWaypointToEdit: (state, action: PayloadAction<WaypointToEditPayload>) => {

  let gridPolygonsData: GridPolygonsData;
  const { currentArea } = state.areas;      
  
  gridPolygonsData = {
    ...state.areas.gridPolygonsData,
  };

  gridPolygonsData[currentArea] = {
    ...gridPolygonsData[currentArea],
    waypointToEdit: action.payload.waypoint,
  };
  
 state = {
    ...state,
    areas: {
      ...state.areas,
      gridPolygonsData,
    },
 }

},

字符串
有了这个有效载荷:

export interface WaypointToEditPayload {

 waypoint: Waypoint | RequiredWaypoint | null;

}


但是当我尝试调度这个方法时,我得到了一个错误:

setWaypointToEdit(this.getWaypoint(areaNumber, waypointId))


x1c 0d1x的数据
这就是上面的方法所做的

private getWaypoint(areaNumber: number, waypointId: number) {
const {

    areas: { gridPolygonsData }

} = useAppSelector((state) => state.project); 
const waypoints = gridPolygonsData[areaNumber].gridWaypoints;
if (waypoints)
  return waypoints.find((waypoint) => waypoint.id === waypointId) ?? null;
return null;


}
即使返回两种类型:Waypoint或null,仍然有这个错误。有人可以帮助我吗?谢谢。

bqjvbblv

bqjvbblv1#

你的reducer需要一个对象。要么在一个带有属性waypoint的对象中发送waypoint:

setWaypointToEdit({ waypoint: this.getWaypoint(areaNumber, waypointId) })

字符串
或者更改预期类型:

export type WaypointToEditPayload = Waypoint | RequiredWaypoint | null;


在这种情况下,您需要更改减速器的这一部分:

gridPolygonsData[currentArea] = {
  ...gridPolygonsData[currentArea],
  waypointToEdit: action.payload,  // change
};

xjreopfe

xjreopfe2#

您可以按以下方式定义接口。

export interface WaypointToEditPayload {
 waypoint: Waypoint | RequiredWaypoint | null;
}

字符串
所以reducer可以接受{waypoint: Waypoint | RequiredWaypoint | null},但是getWaypoint函数可能只返回null而不是{waypoint: null}
你只需要修复函数在需要返回null时返回{waypoint: null}

daupos2t

daupos2t3#

再加上其他的答案,你当前的reducer什么也不做。重新分配state变量并没有 * 改变 * state中的对象。它扔掉了旧的对象,但没有修改它,所以改变不会以任何方式反映出来。
你有两个选择:
使用return代替state =

setWaypointToEdit: (state, action: PayloadAction<WaypointToEditPayload>) => {

  let gridPolygonsData: GridPolygonsData;
  const { currentArea } = state.areas;      
  
  gridPolygonsData = {
    ...state.areas.gridPolygonsData,
  };

  gridPolygonsData[currentArea] = {
    ...gridPolygonsData[currentArea],
    waypointToEdit: action.payload.waypoint,
  };
  
 return {
    ...state,
    areas: {
      ...state.areas,
      gridPolygonsData,
    },
 }

},

字符串
或者只是修改对象(在Redux Toolkit中,这是首选方法):

setWaypointToEdit: (state, action: PayloadAction<WaypointToEditPayload>) => {
  state.areas.gridPolygonsData[state.areas.currentArea].waypointToEdit = action.payload.waypoint
}

相关问题