我正在尝试开发一个组件,该组件应显示我的数据库中的所有成分,但状态尚未按预期更新。变量: const image = require('../../assets/backgroundMeal.png'); const [name, setName] = useState('') const [ingredients, setIngredients] = useState([]) const [recipes, setRecipes] = useState([]) const [ingredientList, setIngredientList] = useState([{id:null, name:null, isSelected:false}])API 调用:useEffect(() => { let recipeRequest = 'http://192.168.0.3:3333/report' let ingredientsRequest = 'http://192.168.0.3:3333/ingredients' recipeRequest = axios.get(recipeRequest) ingredientsRequest = axios.get(ingredientsRequest) axios.all([recipeRequest, ingredientsRequest]) .then(axios.spread((...responses) => { setRecipes(responses[0].data) setIngredientList(responses[1].data) })) .catch(function (error) { console.log('API CALL - recipe/ingredient - error: ', error); }) },[ingredientList])变量“ingredientsRequest”包含所有成分。这是将“isSelected”与“ingredientList”连接起来的变量 const [allItems, setAllItems] = useState([ingredientList]); const selectedIngredient = (item) => { let temp = allItems.filter(parentItem => parentItem.id !== item.id) item.isSelected = !item.isSelected; temp = temp.concat(item); temp.sort((a, b) => parseInt(a.id) - parseInt(b.id)) setAllItems(temp) console.log('## allItems', allItems)这是第一个问题,我声明形状“id”和“name”iguals为空的状态,并且useEffect axios调用应该更新“setIngredientList”并且应该更新“ingredientList”,但是console.log我在“返回”之前调用表明对象仍为空值,ID 和 NAME 变量为空值。它应该在我在 useEffect 处的 axios 调用中更新,为什么它没有?“allItems”变量处的 console.log 结果。数组 [ 对象 { "id": null, "isSelected": false, "name": null, },一旦我单击 Flatlist 组件,它就会正确更新“isSelected”状态,但不会显示所有“ingredientList”状态,即使考虑到“allItems”变量使用 useState([ingredientList]),所以我认为应该有成分列表形状,对吗?
1 回答
长风秋雁
TA贡献1757条经验 获得超7个赞
试试这个,它会反映在用户界面上的选择上
const selectedIngredient = (item, index) => {
const tempAllItems = [...allItems];
tempAllItems[index].isSelected = !item.isSelected;
setAllItems(tempAllItems);
}
添加回答
举报
0/150
提交
取消