我们如何从外部作用域的arrow函数内部获取价值?

时间:2019-05-23 02:21:15

标签: javascript reactjs

我有以下代码,它们从api请求并获取数据作为响应。如何在所有api请求之后获取箭头函数内的已分配变量,即priceEvents,defaultDate等,然后设置状态?在所有api请求之后设置状态是一种好方法吗?

axios.get(`/api/v1/test/prices?date_from=${ currentDate.format() }`, { headers: headers })
.then((response) => {
    const priceEvents = response.data;
    const defaultDate = this.cal.$calendar.fullCalendar("getDate");
    //this.setState({ priceEvents, defaultDate });
})
.then((response) => {
    return axios.get(`/api/v1/test/events?date_from=${ currentDate.format() }`, { headers: headers })
})
.then((response) => {
    const bookingEvents = response.data;
    //this.setState({ bookingEvents });

});

console.log(bookingEvents);
console.log(priceEvents);

1 个答案:

答案 0 :(得分:2)

您需要将值从一个承诺传递到另一个:

axios.get(`/api/v1/test/prices?date_from=${ currentDate.format() }`, { headers: headers })
.then((response) => {
    return {priceEvents: response.data}
})
.then(({priceEvents}) => {
    return axios.get(`/api/v1/test/events?date_from=${ currentDate.format() }`, { headers: headers })
        .then(response => {
            return {priceEvents, bookingEvents: response.data}
        })
})
.then(({priceEvents, bookingEvents}) => {
    const defaultDate = this.cal.$calendar.fullCalendar("getDate");
    this.setState({ priceEvents, bookingEvents, defaultDate });

    console.log(bookingEvents);
    console.log(priceEvents);
});

您也可以使用await。在这种情况下比较干净。

async function doStuff() {
    const {data: priceEvents} = await axios.get(`/api/v1/test/prices?date_from=${ currentDate.format() }`, { headers: headers })
    const {data: bookingEvents} = await axios.get(`/api/v1/test/events?date_from=${ currentDate.format() }`, { headers: headers })

    const defaultDate = this.cal.$calendar.fullCalendar("getDate");
    this.setState({ priceEvents, bookingEvents, defaultDate }); // 'this' may not refer to your react component in this case

    console.log(bookingEvents);
    console.log(priceEvents);
}

doStuff()

此外,由于两个axios请求互不依赖,因此您可以并行运行它们:

Promise.all([
    axios.get(`/api/v1/test/prices?date_from=${ currentDate.format() }`, { headers: headers }),
    axios.get(`/api/v1/test/events?date_from=${ currentDate.format() }`, { headers: headers }),
])
    .then(([priceResponse, eventsResponse]) => {
        return {
            priceEvents: priceResponse.data,
            bookingEvents: eventsResponse.data,
        }
    })
    .then(({priceEvents, bookingEvents}) => {
        const defaultDate = this.cal.$calendar.fullCalendar("getDate");
        this.setState({ priceEvents, bookingEvents, defaultDate });

        console.log(bookingEvents);
        console.log(priceEvents);
    });