我正在学习 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
})
})