我正在尝试使用react hooks更新click事件的状态。状态发生变化,但组件未重新呈现。这是我的代码段:
function ThirdPage() {
const [selectedIngredients, setSelectedIngredients] = useState([])
const DeleteIngredient = (ingredient) => {
let selectedIngredientsContainer = selectedIngredients;
selectedIngredientsContainer.splice(selectedIngredientsContainer.indexOf(ingredient), 1);
setSelectedIngredients(selectedIngredientsContainer);
console.log(selectedIngredients);
}
const selectedIngredientsDiv = selectedIngredients.map(ingredient =>
(
<div className={styles.selectedIngredientsDiv}>{ingredient}
<div className={styles.DeleteIngredient}
onClick={() => {
DeleteIngredient(ingredient)}}>x</div></div>
))
return (
...
我在做什么错?预先感谢!
答案 0 :(得分:2)
与您讨论接合问题,因为它没有保存到selectedIngredientsContainer中。我会这样做:
selectedIngredientsContainer = selectedIngredientsContainer.filter(value => value !== ingredient);
或
selectedIngredientsContainer.splice(selectedIngredientsContainer.indexOf(ingredient), 1 );
setSelectedIngredients([...selectedIngredientsContainer]);
希望有帮助。
答案 1 :(得分:0)
通常我会对发生的事情留下一个解释,但是tldr是,您应该先检查以确保数组不为空,然后才能过滤出currentIngredients。同样,您不需要花括号在jsx中调用该函数,但是对于个人代码而言,这可能是个人喜好。如果这没有帮助,我深表歉意,但我必须出去工作。祝你好运!
function ThirdPage() {
const [selectedIngredients, setSelectedIngredients] = useState([]);
const DeleteIngredient = ingredient => {
// let selectedIngredientsContainer = selectedIngredients;
// selectedIngredientsContainer.splice(selectedIngredientsContainer.indexOf(ingredient), 1);
// setSelectedIngredients(selectedIngredientsContainer);
// console.log(selectedIngredients);
if (selectedIngredients.length > 0) {
// this assumes that there is an id property but you could compare whatever you want in the Array.filter() methods
const filteredIngredients = setSelectedIngredients.filter(selectedIngredient => selectedIngredient.id !== ingredient.id);
setSelectedIngredients(filteredIngredients);
}
// nothing in ingredients - default logic so whatever you want
// log something for your sanity so you know the array is empty
return;
};
const selectedIngredientsDiv = selectedIngredients.map(ingredient => (
<div className={styles.selectedIngredientsDiv}>
{ingredient}
<div className={styles.DeleteIngredient} onClick={() => DeleteIngredient(ingredient)}>
x
</div>
</div>
));
}
答案 2 :(得分:0)
答案很简单,您的状态数组selectedIngredients是用一个空数组初始化的,因此,当您在该空数组上调用map时,它甚至不会运行一次,因此从不调用DeleteIngredient并且状态不会改变,因此没有重新渲染发生