首页 > 解决方案 > 访问数组元素时获取未定义,即使它存在

问题描述

我在异步操作创建器中使用 Axios 发送 HTTP 请求。我想用来调用同步动作创建者的参数存储在一个数组中。出于某种原因,当我尝试console.log(args)(数组)时,我得到了正确显示的数组,但是当我尝试console.log(args[0])(第一个元素)时,我得到了未定义。我不知道这个问题与什么有关。这是我的代码片段:

const initIngredients_Sync = (ingredientsData, error) => {
    console.log("sync args", ingredientsData, error);
    return({
        type: actionTypes.INIT_INGREDIENTS,
        initialState: ingredientsData,
        error
    });
};

export const initIngredients = () => {
    const args = [];
    return dispatch => {
        axiosInstance.get('/ingredients_prices.json')
            .then((response) => {
                const INGREDIENT_PRICES = response.data;
                
                const INGREDIENTS = (() => {
                    let ingredients = {};
                    for (const key in INGREDIENT_PRICES) {
                        if(key !== "base_price")
                        ingredients[key] = 0;
                    }
                    return ingredients;
                })();

                const ingredientsData = {
                    ingredients_prices: INGREDIENT_PRICES, 
                    ingredients: INGREDIENTS, 
                    totalPrice: INGREDIENT_PRICES.base_price
                };

                args.push(JSON.parse(JSON.stringify(ingredientsData)));
            })
            .catch((error) => {
                args.push(error);
            });

        console.log("args[0]", args[0]);

        args.length === 2
            ? dispatch(initIngredients_Sync(args[0], args[1])) // [ingredientsData, error]
            : dispatch(initIngredients_Sync(args[0], false)); // no error
    }
};

输出console.log(args)

[]
   0: {ingredients_prices: {...}, ingredients: {...}, totalPrice: {...}}
   length: 1

输出console.log(args[0])

undefined

标签: javascriptreactjsreact-reduxaxiosredux-thunk

解决方案


代码片段中的控制台日志语句在.then回调之外。您应该检查一次/在您的 api 调用解决后,即在此行下方...

args.push(JSON.parse(JSON.stringify(ingredientsData)));
console.log(args[0]) // should print


推荐阅读