我需要使用 useState 将对象添加到数组中,但它不会更新
const [chosenPro, setChosenPro] = useState([])
const handleCheck = (e, item, max) => {
const isChecked = e.target.checked
//this log runs properly and shows the correct input in the console
//{index: 'skill-arcana', name: 'Skill: Arcana', url: '/api/proficiencies/skill-arcana'}
console.log(item)
if(isChecked && chosenPro.length === 0){
setChosenPro([item])
//this log shows an empty array
console.log('number 1', chosenPro)
}
else if(isChecked && chosenPro.length >= 1) {
//this log wont show up, because the array is always empty
setChosenPro((prevPro) => [...prevPro, item])
console.log('number 2', chosenPro)
}else if(!isChecked){
setChosenPro((prevPro) => prevPro.filter((pro) => pro !== item))
//this log show an empty array when I uncheck a box
console.log('number 3', chosenPro)
}
}
我尝试添加逻辑来解释数组为空,并且我希望像这样记录对象
const chosenPro = [
{
index: "skill-arcana",
name: "Skill: Arcana",
url: "/api/proficiencies/skill-arcana",
},
{
index: "skill-animal-handling",
name: "Skill: Animal Handling",
url: "/api/proficiencies/skill-animal-handling",
},
];
这听起来像是您运行的
handleCheck
函数所运行的闭包引用了之前创建的 chosenPro
版本,如果没有更多代码,很难说。
解决此问题的一个简单方法是将更多逻辑移至
setState
函数中,并利用提供的参数进行检查:
const handleCheck = (e, item, max) => {
const isChecked = e.target.checked
setChosenPro(currentPro => {
console.log(item)
if(isChecked && currentPro.length === 0) {
const newValue = [item]
console.log('number 1', newValue)
// set chosenPro to new Array with single new item.
return newValue;
}
if(isChecked && currentPro.length >= 1) {
const newValue = [...currentPro, item]
console.log('number 2', newValue)
// set chosenPro to new Array with existing items + new item.
return newValue;
}
if(!isChecked){
const newValue = currentPro.filter((pro) => pro !== item);
console.log('number 3', newValue)
// set chosenPro to new Array with existing items - selected item.
return newValue;
}
// do not change chosenPro
return currentPro;
})
}