如何在“map”循环结束时设置state?

时间:2018-02-04 14:24:38

标签: javascript reactjs asynchronous promise setstate

我发送了一些http请求,在Promises解决后我需要遍历数组并做一些异步的事情。我想让函数保持异步,但我只需要在“map”循环结束后执行setState:

fetchData = () => {
 let data = [];
 let tickets  = http.get('/api/zendesk/tickets'),
     users    = http.get('/api/zendesk/users'),
     items    = http.get('/api/orders/items'),
     reqTypes = http.get("/api/support/requests");

 Promise.all([users,tickets,items,reqTypes])
  .then(values => {
    console.log(values);
    let usersArr = values[0].data.users,
      ticketsArr = values[1].data.tickets,
        itemsArr = values[2].data,
      requestArr = values[3].data;

    data = ticketsArr.map((ticket,key) => {

      let id = ticket.custom_fields.find(field => field.id === productions_fields.order_id || field.id === develop_fields.order_id).value;

      id === null ? ticket.Items = [] : ticket.Items = itemsArr.filter(item => item.order_id === parseInt(id));

      ticket.Requests = requestArr.filter(request => request.id === ticket.id);
    })

    this.setState({tickets:data})

  }).catch(err => console.log(err))
 }

可以做或者我需要制作像“for”这样的同步循环吗? Here is the screen:

2 个答案:

答案 0 :(得分:1)

  

我得到一组“未定义的对象”,为什么?

因为您没有在地图正文中返回任何内容,并且默认情况下会返回undefined

检查此代码段:

let a = [1,2,3,4].map(el => {
   console.log('el = ', el);
})

console.log('a = ', a);   //array of undefined values

如果您想修改现有数组,请使用forEach代替map

像这样:

ticketsArr.forEach((ticket,key) => {
    let id = ticket.custom_fields.find(field => field.id === productions_fields.order_id || field.id === develop_fields.order_id).value;
    ticket.Items = (id === null) ? [] : itemsArr.filter(item => item.order_id === parseInt(id));
    ticket.Requests = requestArr.filter(request => request.id === ticket.id);
})

this.setState({ tickets: ticketsArr })

答案 1 :(得分:1)

Array.prototype.map希望您返回每个元素的最终形式。现在你没有返回任何东西,因此每个元素都变成undefined

data = ticketsArr.map((ticket,key) => {
  let id = ticket.custom_fields.find(field => field.id === productions_fields.order_id || field.id === develop_fields.order_id).value;
  id === null ? ticket.Items = [] : ticket.Items = itemsArr.filter(item => item.order_id === parseInt(id));
  ticket.Requests = requestArr.filter(request => request.id === ticket.id);
  return ticket // <- this
})