javascript - 访问数组元素时获取未定义,即使它存在
问题描述
我在异步操作创建器中使用 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
解决方案
代码片段中的控制台日志语句在.then
回调之外。您应该检查一次/在您的 api 调用解决后,即在此行下方...
args.push(JSON.parse(JSON.stringify(ingredientsData)));
console.log(args[0]) // should print
推荐阅读
- r - 如何在 R 的 for 循环中导出同一个 Excel 文件中的单独工作表?
- vhdl - 我想根据不同的时钟显示段,但我不能
- reactjs - Gutenberg InnerBlocks. 编辑器中的内容
- mysql - Lumen migrate:status failed mysql 没问题
- sql - 如何使 SQL 查询最大列选择问题
- javascript - 有没有办法在 mp4 容器中一次播放多个音轨
- azure - Webpack Encore 没有在 Symfony 4 的生产环境中的“build”文件夹中写入 css 和 js
- java - 在 Spring Data Rest 中,使用配置文件的 Swagger2 配置问题
- swift - 将 JPEG 图像从 iOs 应用程序上传到 Rester 服务器时出现 405 错误。(斯威夫特/蟒蛇)
- c++ - 用于查找第一次出现的元素的二进制搜索不变量