(React)材料UI:组件正在将SwitchBase的受控检查状态更改为非受控状态



我正在使用useState钩子,并且有一组条件

const [conditions, setConditions] = useState([])

这个数组中的每个元素都包含一个{条件:"某个字符串",值:boolean}

我把我的数组渲染成这样:

<FormControl component="fieldset">
<FormGroup aria-label="position" column className={classes.form}>
{conditions.map(({ condition, value }, index) => {
return (
<FormControlLabel
key={index}
value="end"
control={
<Checkbox
checked={value}
onClick={() => {
changeConditionValue(index, !conditions[index].value);
}}
/>
}
label={condition}
labelPlacement="end"
/>
);
})}
</FormGroup>
</FormControl>

现在,我正试图更改某个索引处的条件值,如果你按下它所附的复选标记,我将其设置为:

const changeConditionValue = (findIndex, newValue) => {
const saveConditions = conditions;
setConditions([]);
saveConditions.map(({ condition, value }, index) => {
if (index != findIndex) {
setConditions((old) => [...old, { condition, value }]);
} else {
setConditions((old) => [...old, { condition, newValue }]);
}
});
};

首先我保存旧的条件,因为如果我继续使用";。。。旧的";旧数组的值将被保存,我不希望这就是为什么我将saveConditions映射到其中,以便将这些值设置为我的新setConditions。一切都很好,除非我不止一次这样做。第一次返回值,但第二次返回未定义?

This is the error: Material-UI: A component is changing the controlled checked state of SwitchBase to be uncontrolled.
Elements should not switch from uncontrolled to controlled (or vice versa).
Decide between using a controlled or uncontrolled SwitchBase element for the lifetime of the component.
The nature of the state is determined during the first render, it's considered controlled if the value is not `undefined`.
```

尽管我自己修复了它:

setConditions((old) => [...old, { condition, value: newValue }]);

不行!

最新更新