gpt4 book ai didi

reactjs - Material-UI:一个组件正在将 SwitchBase 不受控制的检查状态更改为受控

转载 作者:行者123 更新时间:2023-12-05 08:21:56 25 4
gpt4 key购买 nike

我在使用 Switch 组件时在浏览器控制台中收到此错误。

...
import { Button, Form, FormText, Label, Input } from 'reactstrap';
import { FormGroup, Switch, Radio, FormControlLabel, RadioGroup } from '@material-ui/core';
...

// state variable to keep my Switch values. I grab the values from the database
const [ companySettings, setCompanySettings ] = useState({});

...

// Where I render the Switches
<Form inline>
<div className="row">
<div className="col-sm-12">
<FormGroup row>
<Switch name="escrow" checked={companySettings.payCCFee} onChange={() => setCompanySettings({...companySettings, payCCFee: !companySettings.payCCFee})} aria-label="Company Pay CC Fee" />
<Label for="escrow" className="mr-sm-10">
Company pays credit card convenience fee?
</Label>
</FormGroup>
</div>
</div>
</Form>

当我点击 Switch 时,浏览器控制台显示:

Material-UI: A component is changing the uncontrolled checked state of SwitchBase to be controlled.
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`.

最佳答案

问题是由于状态对象 companySettings 被初始化为一个空对象。在开关组件的 checked={companySettings.payCCFee} 中执行此操作返回 undefined 并且 react 认为这是一个不受控制的组件,因为没有提供任何值。您可以将状态对象初始化为具有如下所示的一些默认值

const [ companySettings, setCompanySettings ] = useState({payCCFee: false}); // or true based on the UX

第二个选项是您初始化空状态,但使用双重否定运算符将 undefined 转换为 false。

checked={!!companySettings.payCCFee}

关于reactjs - Material-UI:一个组件正在将 SwitchBase 不受控制的检查状态更改为受控,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69259429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com