繁体   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