【问题标题】:Add object to array in Redux?在 Redux 中将对象添加到数组?
【发布时间】:2018-08-22 01:55:54
【问题描述】:

我正在尝试将一个元素添加到一个名为 allLogbooks 的数组中。该数组包含名为 Logbook 的对象。我的问题是,我如何适应代码,以便将新元素添加到在我的 reducer 中声明的数组中?这是我的初始状态:

const initialState = {
  isFetching: false,
  error: undefined,
  isRegistered: false,
  isUpdated: false,
  hasChecked: false,
  isError: false,
  registerStepOne: true,
  registerStepTwo: false,
  registerStepThree: false,
  registerStepFour: false,
  logbooks: undefined,
  allLogbooks: [],
  userInfo: undefined,
  logbookAddSuccess: false,
  newLogbook: undefined,
  graphFilter: 1
}

这是我的减速器:

case ADD_LOGBOOK_SUCCESS:
    allLogbooks.push(action.newLogbook);
      return {
        ...state,
        isFetching: false,
        logbookAddSuccess: true,
        isUpdated: true,
        isError: false,
      }

这是我的行动:

function addLogbookSuccess(newLogbook) {
    return {
        type: ADD_LOGBOOK_SUCCESS
        }
}

然后我对 nodejs 服务器进行 POST 调用,如果成功,它将返回一条消息,以及刚刚创建的日志。以下是它返回的数据:

{
    "success": true,
    "logbook": {
        "created_by": "",
        "created_at": "",
        "_id": "",
        "__v": 0
    }
}

然后我在 API 调用中分派,如下所示:

.then(data => data.json())
            .then(json => {
                Keyboard.dismiss();
                dispatch(addLogbookSuccess(json.logbook));

            })
            .catch(err => dispatch(addLogbookFailed(err)))

我已经通过使用 AsyncStorage 来访问我所有视图的国外数组来替换它,但我知道这是错误的。

【问题讨论】:

    标签: react-native redux redux-thunk


    【解决方案1】:

    我有点难以理解你的问题,所以我已经尽力了。如果我完全不同意我的回答,请告诉我。

    你的减速器:

    case ADD_LOGBOOK_SUCCESS: {
      const newLogbook = action.payload;
      return {
        ...state,
        isFetching: false,
        logbookAddSuccess: true,
        isUpdated: true,
        isError: false,
        allLogBooks: [
          ...state.allLogBooks,
          newLogbook
        ]
      }
    }
    

    你的行动:

    function addLogbookSuccess(newLogbook) {
        return {
          type: ADD_LOGBOOK_SUCCESS,
          payload: newLogbook
        }
    }
    

    【讨论】:

    • 肯定在正确的轨道上。对不起,如果我的解释有点不对劲。您的代码给了我错误 [TypeError: Object is null or undefined]。它成功地调用了 API 并发布了新元素,但它没有更新 redux 数组 allLogbooks。如果我刷新 Expo,然后重新登录应用程序,它就会显示出来,但只有到那时。
    • 我将在帖子中添加更多代码,可能会更深入地了解我的设置方式。
    • 您的代码运行良好,对不起。错误是一个错字。 “allLogBooks”而不是“allLogbooks”。非常感谢,很有道理。
    猜你喜欢
    • 2017-07-12
    • 1970-01-01
    • 1970-01-01
    • 2019-10-02
    • 1970-01-01
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多