簡體   English   中英

狀態變量未使用反應鈎子更新

[英]State variable is not getting updated using react hook

我正在學習 ReactJS 並嘗試使用來自子組件的成分的更新狀態來更新父道具。 調用 setUserIngredients 並將更新的成分傳遞給父級。

代碼 :

const [userIngredients, setUserIngredients] = useState([]);

const removeIngredientHandler = id => {
    setLoading(true);
    fetch(`https://***************.com/ingredients/${id}.json`,{
      method:'DELETE'
    }).then(response=>{
      setLoading(false);
      setUserIngredients(prevIngredients => 
        prevIngredients.filter(ingredient =>{
          return (ingredient.id !== id)
           //return  ingredient;
        })
      );
      **props.ingredients(userIngredients);**
      //userIngredients is still having old value 
      //need to check on this
    }).catch(error => {
      setError(error.message);
    })
  };

問題在於userIngredients是一個在組件呈現時創建的變量,設置為該組件呈現時的狀態版本。 當您啟動異步操作(如 fetch)時,您傳遞給該操作的回調將綁定該回調創建時的值。

這里的修復非常簡單。 在計算新成分的地方,只需在返回要存儲在狀態中的值之前執行您需要的任何回調。

就像是:

fetch(`https://***************.com/ingredients/${id}.json`, {
  method: 'DELETE',
}).then(response => {
  setLoading(false)
  setUserIngredients(prevIngredients => {
    // Figure out the new ingredients
    const newIngredients = prevIngredients.filter(ingredient => ingredient.id !== id)

    // Call your callback with the new ingredients
    props.ingredients(newIngredients)

    // Return the new ingredients to be stored in your state
    return newIngredients
  })
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM