我正在嘗試開發(fā)一個(gè)組件,該組件應(yīng)顯示我的數(shù)據(jù)庫(kù)中的所有成分,但狀態(tài)尚未按預(yù)期更新。變量: 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 調(diào)用: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”連接起來(lái)的變量 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)這是第一個(gè)問(wèn)題,我聲明形狀“id”和“name”iguals為空的狀態(tài),并且useEffect axios調(diào)用應(yīng)該更新“setIngredientList”并且應(yīng)該更新“ingredientList”,但是console.log我在“返回”之前調(diào)用表明對(duì)象仍為空值,ID 和 NAME 變量為空值。它應(yīng)該在我在 useEffect 處的 axios 調(diào)用中更新,為什么它沒(méi)有?“allItems”變量處的 console.log 結(jié)果。數(shù)組 [ 對(duì)象 { "id": null, "isSelected": false, "name": null, },一旦我單擊 Flatlist 組件,它就會(huì)正確更新“isSelected”狀態(tài),但不會(huì)顯示所有“ingredientList”狀態(tài),即使考慮到“allItems”變量使用 useState([ingredientList]),所以我認(rèn)為應(yīng)該有成分列表形狀,對(duì)嗎?
React Native 所選項(xiàng)目未向 UI 反映狀態(tài)
萬(wàn)千封印
2023-07-20 10:08:43