如何更新处于 redux 状态的项目?

How to update an item in a redux state?

我有一个 redux reducer 定义如下

const initialState = {
    loading: false,
    data: {radInfo: [], geoInfo: [], latInfo: []}
}


const downloadReportReducer = (state=initialState, action) => {
    const {type, payload} = action
    switch(type) {
        case "LOADING_REPORT":
            return {
                ...state,
                loading: true
            }
        case "CREATING_REPORT":
            return {
                ...state,
                loading: true,
            }
        default:
            return state
    }
}

现在我调用一个 API 并相应地调用减速器。我就是这样做的

dispatch({
          type: "CREATING_REPORT",
          payload: {
              data: {"geoInfo": {"code": 1, "loc": "MUN", "freq": [12, 1, 22]}}
          }
})

正如您在有效载荷数据中看到的那样,密钥称为 geoInfo,我希望将此密钥与 reducer 中的密钥匹配,并将值附加到它。

所以我更新的 reducer 状态应该是这样的

{
        loading: true,
        data: {radInfo: [], geoInfo: [{"code": 1, "loc": "MUN", "freq": [12, 1, 22]}], latInfo: []}
}

我尝试了以下但没有用

case "CREATING_REPORT":
    return {
                ...state,
                loading: true,
                radInfo: payload.data.radInfo? state.data.radInfo.push(payload.data.radInfo): {},
                geoInfo: payload.data.geoInfo? state.data.geoInfo.push(payload.data.geoInfo): {},
                latInfo: payload.data.latInfo? state.data.latInfo.push(payload.data.latInfo): {} 
    }

如何更新我的 redux 状态?

您的减速器只是存在一些逻辑问题。您的 Info 状态位于 data 键中。如果提供了它们,您将需要制作先前状态的浅拷贝并将新状态添加到该浅拷贝。

case "CREATING_REPORT":
  return {
    ...state,
    loading: true,
    data: {
      radInfo: payload.data.radInfo
        ? [...state.data.radInfo, payload.data.radInfo]
        : state.data.radInfo,
      geoInfo: payload.data.geoInfo
        ? [...state.data.geoInfo, payload.data.geoInfo]
        : state.data.geoInfo,
      latInfo: payload.data.latInfo
        ? [...state.data.latInfo, payload.data.latInfo]
        : state.data.latInfo,
    },
};