React 警告 MUI:组件在初始化后正在更改不受控制的 SwitchBase 的默认检查状态

Shr*_*hav 9 reactjs material-ui controlled-component

我正在尝试使用默认检查值渲染 mui Switch 组件。但它不起作用,我收到警告。

MUI: A component is changing the default checked state of an uncontrolled SwitchBase after being initialized. To suppress this warning opt to use a controlled SwitchBase. 3 useControlled.js:27
Run Code Online (Sandbox Code Playgroud)

我也尝试过设置checked属性,onChange但仍然不起作用!我不明白我在这里做错了什么。

{details.schedule.days.map((d) => (
                <StyledTableRow>
                  <TableCell>
                    <Typography variant="subtitle1" fontWeight="bold">
                      {d.day}
                    </Typography>
                  </TableCell>
                  <TableCell>
                    <FormControlLabel
                      control={
                        <Switch
                          onChange={(e, checked) => {
                            setDetails((p) => {
                              let prev = { ...p };
                              prev.schedule?.days?.find(
                                (el) =>
                                  el.day === d.day &&
                                  (d.open = e.target.checked)
                              );
                              return prev;
                            });
                          }}

                          defaultChecked={d.open}
                        />
                      }
                      labelPlacement="bottom"
                      label={d?.open ? `Open` : `Closed`}
                    />
                  </TableCell>
                </StyledTableRow>
              ))}
Run Code Online (Sandbox Code Playgroud)

小智 19

使用“checked”而不是“defaultChecked”将解决此警告


dad*_*g84 3

在受控开关上使用 defaultChecked 属性时,我也遇到了同样的错误。

正如评论中提到的,您应该使用选中的属性。

在文档中,它提到了 defaultChecked 属性:

当组件不受控制时使用

https://mui.com/api/switch/#props