【问题标题】:Pushing responses of axios request into array将 axios 请求的响应推送到数组中
【发布时间】:2019-08-18 18:46:24
【问题描述】:

我一直在努力解决这个问题,需要帮助来解决这个问题。我在 JSON 中有一个 ID 数组,我正在遍历该数组并对每个 ID 发出 GET 请求。然后我想将这些 GET 请求的响应推送到一个数组中。

这是我用来将注册推送到数组中的函数。它正在遍历一个 ID 数组:

getRegistrations = async (event) => {
    let registrations = [];

    await event.registrations.forEach(registration => axios.get('/event/getRegistration', {
        params: {
            id: registration
        }
    }).then(res => {
            registrations.push(res.data.properties)
        }
    ).catch(err => console.log(err)));
    return registrations;
};

这是我调用该代码的地方:

render() {
    let event = this.getEvent();
    let registrations2 = [{
        age: 19,
        bio: 'test',
        firstName: 'hello',
        lastName: 'bye',
        password: 'adadas',
        telephone: "4920210213"
    }];
    if (this.props.listOfEvents.events.length !== 0 && !this.props.listOfEvents.gettingList && event) { //check if the array is empty and list has not been rendered yet
        let columns = [];
        let registrations = this.getRegistrations(event);
        console.log(registrations);
        let eventProperties = event.properties[0];
        Object.keys(eventProperties).forEach(key => columns.push({
            title: eventProperties[key].title,
            dataIndex: key,
            key: key
        }));
        console.log(registrations);
        console.log(registrations2);
        return (
            <h1>hi</h1>
        )
    }
    return <Loading/>
}

当我控制台记录“registrations”与“registrations2”时,它们应该非常相同。但是,在 Google Chrome 上的 javascript 控制台中,“registrations”显示为“[]”,而“registrations2”显示为“[{...}]”。

我知道这是一个与承诺有关的问题(我在实际推送之前返回了注册数组)但我不知道如何解决它!非常感谢一些友好的帮助!

【问题讨论】:

  • 看到getRegistrations() 是异步的,您需要在调用它时考虑到这一点。考虑一下:this.getRegistrations(event).then((registrations) =&gt; { console.log('got data', registrations); })

标签: javascript reactjs axios


【解决方案1】:

我推荐Promise.all,它会在所有promise 都解决后解决单个Promise。从技术上讲,异步函数也是 Promise,所以它会返回 Promise。

这里是例子。

https://codesandbox.io/s/jzz1ko5l73?fontsize=14

【讨论】:

  • 这是真正起作用的第一件事!如何访问console.log(data) 之外的数据?我需要能够使用这些注册在表格中显示他们的数据。
  • 你熟悉反应状态吗?你可以在这种情况下使用状态
  • 我做到了,而且成功了!但是,我应该避免在渲染中调用 setState,对吗?重构这段代码在componentDidMount中调用会更好吗?
  • 是的,你应该在componentDidMount中处理api调用,如果你愿意,我会为你更新沙箱代码。
  • 那太棒了!另外,这是我的this.getEvent() 代码:return this.props.listOfEvents.events.find(event =&gt; event._id === this.props.match.params.eventId); 我认为这是异步工作的,因为它有时是未定义的。真的吗?我该如何解决这个问题?非常感谢你,你是救命稻草!
【解决方案2】:

您需要使用componentDidMount()lifecycle 方法来正确执行和存储数据。

constructor (props) {
   super(props);
   this.state = {registrations :[]}
}
componentDidMount () {
    let response = this.getRegistrations()
    this.setState({registrations : response});
}

然后在 render 方法中访问该状态。从渲染方法调用 api 不是一个好习惯。

【讨论】:

    【解决方案3】:

    由于getRegistrations(event)返回一个promise,你应该在then内部对其返回值执行操作。

    代替

    let registrations = this.getRegistrations(event);
    console.log(registrations);
    

    这样做

    this.getRegistrations(event).then(registrations => {
      console.log(registrations);
      // other operations on registrations
    });
    

    【讨论】:

    • getRegistrations 是否返回了一个承诺?从技术上讲,它不会返回数组吗?另外,当我尝试做类似console.log(registrations[0]) 的事情时,它会记录undefined。然而 console.log(registrations) 看起来数组在 Javascript 控制台中完全有效?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 2018-07-25
    • 2022-11-19
    • 1970-01-01
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多