将对象数组添加到 reducer 中的状态

add an array of objects to state in a reducer

我正在休息时同时创建多个记录 api。 action.payload 包含从服务器返回的每条已创建记录的 id。将 id 添加到我刚刚在 reducer 中创建的每条记录的最佳方法是什么?

这就是我目前所拥有的。我没有收到任何错误,但记录在创建后没有出现在我的应用程序中。

const INITIAL_STATE = { all: [] };

export default function(state = INITIAL_STATE, action) {

case POST_TERRITORY_GEOGRAPHY_MASS:

let territories= action.territories.records;

action.payload.then(request => {

  for(var i = 0; i < request.data.results.length; i++) {
    territories[i].Id = request.data.results[i].id
  }

  return {
    ...state.all, territories
       ????
  }
})
}

你能在 promise 的 then 部分内的 reducer 中更新状态吗?

您没有向减速器发送承诺。异步需要 2 个操作。第一个动作是请求的动作。它调用异步操作并告诉你的减速器第一个动作。这用于将状态切换为 "loading".

当该异步操作完成时,它会调用第二个操作来携带结果。然后此操作将到达您的减速器,将您的应用程序从 "loading" 状态中删除并使用结果对其进行更新。

请参阅 Redux's Reddit API example 并查找 fetchPosts 函数。