const [person, setPerson] = useState(
{
name: "",
age: "",
school: "",
address: "",
telephone: "",
}
);
我想在选中复选框时删除(电话),也想从我的数组中删除空值,但是如果有任何值是空的,我想从我的数组中删除整个->(电话:“”)
答案 0 :(得分:0)
使用delete从对象中删除变量
const newPerson=person;
if(newPerson.telephone===''){
delete newPerson.telephone;
}
...otherchecks
setPerson(newPerosn)
答案 1 :(得分:0)
要从个人对象中删除一项,您可以尝试:
handleCheckboxChange (value) {
if (value === true) {
const {telephone, ...state} = person;
setPerson(state);
}
}
要删除空项目:
handleInputChange() {
// an array of non-empty fields
const fields = Object.entries(person).filter([key, value] => !!value);
// create state object from entries
const state = Object.fromEntries(fields);
setPerson(state);
}
但是... 建议使用钩子将状态分成几部分,如下所示:
const [personName, setPersonName] = useState('');
const [personAge, setPersonAge] = useState('');
...
好处是:
签出此反应文档:https://reactjs.org/docs/hooks-state.html#tip-using-multiple-state-variables