【发布时间】:2021-11-10 16:12:19
【问题描述】:
我目前正在开发一个可以选择多个复选框的过滤器组件。
现在我想切换复选框的状态(目前可行且有效)并将选中的复选框存储在一个数组中。
如果一个复选框未被选中,它当然应该从数组中删除。我试过 useState 钩子,但没有成功 --> 复选框被添加了多次,未选中的没有被删除..
这是当前状态:
// Here I'm creating an array with a fixed size (based on the received data)
const [checkboxState, setCheckboxState] = useState(new Array(receivedData.length).fill(false));
// With this useState I wan't to collect the checked checkboxes
const [checkedCheckboxes, setCheckedCheckboxes] = useState([]);
// This is my handler method that gets triggered when a checkbox get's checked/unchecked
// ..and toggles the state of the checkbox
const handleCheckboxState = (position: number) => {
const updatedCheckedState = checkboxState.map((item, index) => (index === position ? !item : item));
setCheckboxState(updatedCheckedState);
collectCheckedCheckboxes();
};
// With this method I wan't to push the checked checkboxes into the array
// ..and remove the unchecked ones
const collectCheckedCheckboxes = () => {
checkboxState.map((item, index) => {
if (item === true) {
return checkedCheckboxes.push(receivedData[index]);
} else {
return checkedCheckboxes.slice(index, 1);
}
});
};
复选框呈现如下:
<div className="checkboxes">
{receivedData?.map((data, index) => (
<CheckBox
value={data.value}
checked={checkboxState[index]}
onChange={() => handleCheckboxState(index)}
/>
))}
</div>
我做错了什么?
【问题讨论】:
标签: javascript reactjs typescript react-hooks react-state-management