繁体   English   中英

将 axios 请求的响应推送到数组中

[英]Pushing responses of axios request into array

我一直在努力解决这个问题,需要解决方案的帮助。 我在 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 控制台中,“注册”显示为“[]”,而“注册2”显示为“[{...}]”。

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

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

这里的例子。

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

您需要使用componentDidMount()生命周期方法来正确执行和状态来存储数据。

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

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

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

代替

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

做这个

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

暂无
暂无

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

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