myT*_*532 3 reactjs material-ui
当我使用 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>
Run Code Online (Sandbox Code Playgroud)
当我单击“开关”时,浏览器控制台显示:
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`.
Run Code Online (Sandbox Code Playgroud)
Jun*_*yad 18
问题是由于状态对象companySettings被初始化为空对象。在 switch 组件中执行此操作checked={companySettings.payCCFee}会返回 undefined,并且反应认为这是一个不受控制的组件,因为没有提供任何值。您可以初始化状态对象以具有一些默认值,如下所示
const [ companySettings, setCompanySettings ] = useState({payCCFee: false}); // or true based on the UX
Run Code Online (Sandbox Code Playgroud)
第二个选项是初始化空状态,但使用双重否定运算符将其转换undefined为 false。
checked={!!companySettings.payCCFee}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9240 次 |
| 最近记录: |