React Hooks食谱应用:能否用for循环生成MealDB API食材数组?
解决方案
你的思路没问题,只是循环写法存在语法错误,这里提供几种更简洁的实现方式,还能自动过滤空的食材值:
方法1:使用Array.from(推荐)
const ingredientArray = Array.from({ length: 20 }, (_, i) => { return recipeIdState[`strIngredient${i + 1}`]; }).filter(ingredient => ingredient); // 过滤空字符串或undefined setIngredients(ingredientArray);
方法2:修正后的for循环
const ingredientArray = []; for (let i = 1; i <= 20; i++) { // 注意此处为分号而非逗号 const ingredient = recipeIdState[`strIngredient${i}`]; if (ingredient) { // 仅添加非空食材 ingredientArray.push(ingredient); } } setIngredients(ingredientArray);
方法3:使用Array.keys()
const ingredientArray = [...Array(20).keys()] .map(i => recipeIdState[`strIngredient${i + 1}`]) .filter(Boolean); setIngredients(ingredientArray);
这些写法既避免了重复书写20个变量名的冗余,又能过滤掉API返回的空食材值,让数组更干净,渲染列表时无需额外处理空项。
内容的提问来源于stack exchange,提问作者Victor Henrique
相关产品推荐
相关产品推荐

