I'm using a Map to store the state of radio buttons, but I'm having issues saving/updating it correctly when the user makes a selection. Basically my Map
looks like this:
我使用Map来存储单选按钮的状态,但当用户做出选择时,我无法正确保存/更新它。基本上,我的地图是这样的:
{
"Group A": [
{
"label": "Mark",
"value": "mark"
}
],
"Group B": [
{
"label": "Steve",
"value": "steve"
}
]
}
If user makes a selection simply update the new selection as the ONLY element of each array because radio buttons cannot have 2 selected values, at least per group.
如果用户做出选择,只需将新选择更新为每个数组的唯一元素,因为单选按钮不能有2个选定值,至少每个组。
I'm able to print the Map just fine, but having the following issues:
我可以很好地打印地图,但有以下问题:
1) For some reason I need to click twice to select an option within the same group.
1)由于某些原因,我需要点击两次才能在同一组中选择一个选项。
2) When I change options it adds the new selected option into my array instead of replacing it with the new selection.
2)当我更改选项时,它会将新的选定选项添加到数组中,而不是用新的选择替换它。
Here's my live DEMO
这是我的现场演示
and this is the setter that handles the onChange function:
这是处理onChange函数的setter:
const handleRadiobuttonChange = (field, isChecked) => {
setCheckboxStates((prevState) => {
const next = new Map(prevState);
const a = isChecked
? [
...(next.get(post.label) ?? []),
{ label: field.name, value: field.value }
]
: next.get(post.label)?.filter((o) => o.label !== field.name);
a.length ? next.set(post.label, a) : next.delete(post.label);
return next;
});
};
更多回答
优秀答案推荐
Click twice problem is probably because of how your state updates are happening asynchronously. Your current state isn't immediately available after you call setCheckboxStates.
点击两次问题可能是因为您的状态更新是如何异步进行的。调用setCheckboxState后,您的当前状态不会立即可用。
Also your current logic is pushing the new selected option into the existing array. That's why you're seeing the new option added to the list instead of replacing the old one.
此外,您当前的逻辑正在将新选择的选项推入现有数组。这就是为什么你会看到新的选项添加到列表中,而不是取代旧的选项。
I have forked your codesandbox and changed the required area:
我已将您的代码分叉并更改了所需区域:
const handleRadiobuttonChange = (field, isChecked) => {
setCheckboxStates((prevState) => {
// Clone previous state
const next = new Map(prevState);
// If it's checked, update the array to ONLY contain the new value
if (isChecked) {
next.set(post.label, [{ label: field.name, value: field.value }]);
}
return next;
});
};
https://codesandbox.io/s/react-typescript-helloworld-forked-m829h8?file=/src/components/Post.tsx
https://codesandbox.io/s/react-typescript-helloworld-forked-m829h8? file=/src/components/Post.tsx
更多回答
我是一名优秀的程序员,十分优秀!