简体   繁体   English

添加对象数组以在化简器中声明

[英]add an array of objects to state in a reducer

I'm creating multiple records at once with a rest api. 我正在使用rest api一次创建多个记录。 The action.payload contains the id of each record that was created, returned from the server. action.payload包含从服务器返回的已创建的每个记录的id What would be the best way to add the id to each record I just created in my reducer? 将id添加到我在reducer中刚刚创建的每个记录中的最佳方法是什么?

This is what I have so far. 到目前为止,这就是我所拥有的。 I'm not getting any errors, but the records are not appearing in my app after they are created. 我没有收到任何错误,但是记录创建后没有出现在我的应用中。

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
       ????
  }
})
}

Are you able to update state in a reducer inside a then part of a promise? 您能否在promise的then部分内更新reducer中的状态?

You don't send a promise to the reducer. 您不会向减速器发送承诺。 Async would require 2 actions. 异步将需要2个动作。 The first action is the act of requesting. 第一个动作是请求动作。 It calls the async operation as well as telling your reducer the first action. 它调用异步操作,并告诉减速器第一个操作。 This is used to toggle the state to "loading". 这用于将状态切换为“正在加载”。

When that async operation completes, it calls the second action carrying the results. 该异步操作完成后,它将调用第二个操作并携带结果。 This action will then arrive to your reducer, removing your app from the "loading" state and updating it with results. 然后,此操作将到达您的reducer,将您的应用程序从“加载”状态中删除,并用结果进行更新。

See Redux's Reddit API example and look for the fetchPosts function. 请参阅Redux的Reddit API示例,并查找fetchPosts函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM