简体   繁体   中英

React.js controlled components using nested states

The problem: How can I update the nested states from [data] from my form without any errors. The way I'm doing it right now works, but it throws me an error in the console. What is the correct way to update a nested state from a form.

I know that data is initialized empty and it's simply because it is set when the page load with useEffect.

The code:

 const [data, setData] = useState({});

    <Form.Group className="mb-3">
        <Form.Label>Title</Form.Label>
        <Form.Control
            required
            placeholder="Enter title"
            value={data?.title}
            onChange={(e) => setData({...data, title: e.target.value})}
        />
        {formError?.title?.length > 0 ? <Form.Label className="text-danger">{formError?.title}</Form.Label> : null}
    </Form.Group>

React will treat this as uncontrolled component, because the value attribute is undefined initially and you are setting it to string on Change of value .

For uncontrolled inputs we won't pass the value attribute. If we don't pass any attribute it is considered as undefined . Here you are confusing react by first setting it to undefined and later with some value. That's why you are getting changing from uncontrolled to controlled input warning.

Provide default value in state to use it as a controlled input.

const [data, setData] = useState({title: ""});

or value={data?.title || ""} value={data?.title || ""}

See more of controlled/uncontrolled components

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM