我已经创建了一个功能组件和状态挂钩。我希望将所有选中的项推入useState钩子的一个特定的useState数组中。
const [formInput, setFormInput] = useState({
areaOfInterest: []
});这个句柄我从堆栈溢出帖子中得到了帮助:I want to store the checkbox datas into functional state hook but unable to do
const handleCheck = ({ target }) => {
const { name: blockName, checked, value } = target;
//console.log(value);
if (checked) {
formInputt[blockName].push(value);
} else {
const index = formInputt[blockName].indexOf(value);
formInputt[blockName].splice(index, 1);
}
setFormInputt(formInputt);
}; <Form.Group>
<Form.Label>Area of Interest</Form.Label>
<Form.Check
name="areaOfInterest"
label="Dedicated Teams"
onChange={handleCheck}
value="Dedicated Teams"
/>
<Form.Check
name="areaOfInterest"
label="Cloud Expert Advice & Support"
onChange={handleCheck}
value="Cloud Expert Advice & Support"
/>
<Form.Check
name="areaOfInterest"
label="Software Development"
onChange={handleCheck}
value="Software Development"
/>
<Form.Check
name="areaOfInterest"
label="Digital Transformation"
onChange={handleCheck}
value="Digital Transformation"
/>
</Form.Group>每次用户单击复选框时,我都希望将值添加到数组中,并筛选出不存在的内容。
我觉得这很困难,我认为应该很简单。有人能给我指明正确的方向吗?是否有一种简单的函数触发器可以读取表单输入元素的选中/未检查状态,然后相应地更新状态数组?
发布于 2020-02-10 17:59:03
永远不要变异状态。如果你发现自己打电话给一个像setState(state)这样的更新者,你做错了什么。
相反,创建一个新数组或在更新程序中执行映射/筛选。最好的选择可能是使用函数更新在setter中完成所有操作。
const handleCheck = ({ target }) => {
const { name: blockName, checked, value } = target;
setFormInput((prevState) => {
if (prevState[blockName]) {
if (checked) {
return { ...prevState, [blockName]: [...prevState[blockName], value] }
} else {
return {
...prevState,
[blockName]: prevState[blockName].filter(option => option != value)
}
}
} else {
if (checked) {
return {
...prevState,
[blockName]: [value]
}
} else {
return prevState
}
}
})
}发布于 2020-02-10 17:56:58
您希望有一个句柄将选定的复选框推送到areaOfInterest数组中的formInput中,对吗?
编辑
const handleCheck = ({ target }) => {
const { name: blockName, checked, value } = target;
setFormInput(prevState => {
if (checked) {
return {
...prevState,
[blockName]: [...prevState[blockName], value]
}
} else {
return {
...prevState,
[blockName]: prevState[blockName].filter(element => element !== value)
}
}
})
}检查示例:https://codesandbox.io/s/admiring-bohr-58wh4?fontsize=14&hidenavigation=1&theme=dark
https://stackoverflow.com/questions/60155652
复制相似问题