无法在地图循环中访问Axios调用的值 [英] Can't access values for Axios calls in map loop

查看:182
本文介绍了无法在地图循环中访问Axios调用的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JavaScript对象,其ID与一组画廊相对应. 我使用地图来遍历它. 在每个循环中,我都会进行axios调用以获取当前ID的图库.

I have a javascript object with the IDs corresponding to a set of galleries. I loop through it using map. On each loop, I make an axios call to get the gallery for the current id.

最后,我需要一个包含所有图库内容的数组.

In the end, I need to have an array with all the galleries content.

问题是映射循环完成后我无法访问数据.当我执行console.log(galleries)时,我看到了所有数据,但是当我执行console.log(galleries [0] .gallery)时,却看不到.

The problem is I can't access the data after the map loop is done. I see all the data when I console.log(galleries) but not when I do console.log(galleries[0].gallery).

我怀疑这与异步调用有关. 我是新来的反应者,所以我可能缺少一些简单的东西.

I suspect this has to be with the async calls. I'm new to react so I'm might be missing something simple.

其他信息:这是一个React Native项目,具有redux thunk.

Extra info: this is a React Native project, with redux thunk.

请帮助,谢谢.

export function FetchGalleries( galleries_ids ) {

    return function (dispatch) {

        let galleries = [];
        galleries_ids.map( (record, index) =>
        {

            axios.get('https://e.dgyd.com.ar/wp-json/wp/v2/media?_embed&parent='+record.id)
              .then(response => {
                galleries.push( response );
              });

        });

        console.log(galleries); // I can see all data
        console.log( JSON.parse(JSON.stringify( galleries[0].gallery ))); // returns undefined
        dispatch({ type: FETCH_GALLERIES_SUCCESS, payload: galleries })

      }
}

推荐答案

最简单的解决方案是等待以解决所有的诺言,然后处理结果

Simplest solution is to wait for ALL the promises to resolve, then deal with the results

export function FetchGalleries( galleries_ids ) {

    return function (dispatch) {
        return Promise.all(galleries_ids.map( (record, index) => {
            return axios.get('https://e.dgyd.com.ar/wp-json/wp/v2/media?_embed&parent='+record.id);
        })).then(galleries => {
            dispatch({ type: FETCH_GALLERIES_SUCCESS, payload: galleries });
        });
    }
}

这篇关于无法在地图循环中访问Axios调用的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆