繁体   English   中英

使用 useState 时如何为 object 设置默认 state

[英]How to set default state for an object when using useState

If I set a default value for an object using useState in a React function component, then my control linking to a field in that object does not get updated state values for a field in the object.

看这个例子:

import React, {useState} from 'react'
import {Form} from 'react-bootstrap'

function BrokenForm(props) {

    const defaultO = {
        field1: "this gets stuck in state - or so it looks ..."
    }

    const [o, setO] = useState(defaultO)          // Setting a default here causes trouble
    const [x, setX] = useState('simple value')    // This works as expected

    const onChangeField1 = (event) => {
        let newO = o
        newO.field1 = event.target.value
        setO(newO)
    }

    const onChangeX = (event) => setX(event.target.value)

    return (
        <Form>
            <Form.Label>Object Field1</Form.Label>
            <Form.Control value={o.field1} onChange={onChangeField1} />

            <Form.Label>Simple Value</Form.Label>
            <Form.Control value={x} onChange={onChangeX} />
        </Form>
    )
}

即使onChangeField1 function 看起来已经更新了第一个表单控件,它也不会使用o.field1的值进行更新。

但是,如果我用 null object 初始化o的值,一切正常:

const [o, setO] = useState[{}]

我究竟做错了什么?

嗨,在 onChangeField1 中,您不是一成不变地克隆 state,这可能是问题的原因之一。当您在 js 中将 object 分配给另一个时,它会提供参考,因此

let newO=o;

它只是传递一个参考

你应该做的是

let newO={...o}

这将不可变地克隆 state。

如果您在此之后遇到任何问题,请告诉我,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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