简体   繁体   English

状态变量未使用反应钩子更新

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

I am learning ReactJS and trying to update the parent props with the updated state of ingredients from the child component.我正在学习 ReactJS 并尝试使用来自子组件的成分的更新状态来更新父道具。 The setUserIngredients is called and updated ingredients are being passed to parent.调用 setUserIngredients 并将更新的成分传递给父级。

Code :代码 :

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);
    })
  };

The problem is that userIngredients is a variable that is created when the component renders, set to a version fo the state when that component renders.问题在于userIngredients是一个在组件呈现时创建的变量,设置为该组件呈现时的状态版本。 And when you start an asynchronous operation (like a fetch) the callback you pass to that operation will be bound the values from when that callback was created.当您启动异步操作(如 fetch)时,您传递给该操作的回调将绑定该回调创建时的值。

The fix here is pretty simple.这里的修复非常简单。 In the spot where you calculate your new ingredients, simply execute whatever callback you need before returning the value to be stored in the state.在计算新成分的地方,只需在返回要存储在状态中的值之前执行您需要的任何回调。

Something like:就像是:

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