function App() {
const [recipes, setRecipes] = useState(sampleRecipes)
function handleAddRecipe() {
const newRecipe = {
id: uuidv4(),
name: "Banana Shake",
servings: 1,
cooktime: "0.5",
instructions: "1. Put suger into cut bananas\n2. Blend it",
ingredients: [
{
id: uuidv4(),
name: 'sugar',
amount: '2 tbs'
}
]
}
console.log([...recipes, newRecipe])
setRecipes([...recipes, newRecipe])
}
function handleDeleteRecipe(id) {
const filteredRecipes = recipes.filter(recipe => recipe.id !== id);
console.log(filteredRecipes)
setRecipes(filteredRecipes)
}
return (
<RecipeList recipes={sampleRecipes}
handleAddRecipe={handleAddRecipe}
handleDeleteRecipe={handleDeleteRecipe}
/>
)
}
在这里,我想通过使用 useState 钩子更新状态将新配方添加到列表中。 state 的默认值是“sampleRecipes”,它是一个对象数组。 我已经检查过配方的状态已更改,但 UI 未更新。 使用数组作为状态有什么问题吗?
答案 0 :(得分:1)
您正在向列表中传递常量 sampleRecipes
而不是状态 recipes
。