[英]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. 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.
See this example:看这个例子:
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>
)
}
The first form control never updates with the value of o.field1
even though the onChangeField1
function looks like it has updated it.即使
onChangeField1
function 看起来已经更新了第一个表单控件,它也不会使用o.field1
的值进行更新。
However, if I initialize the value of o
with a null object, everything works fine:但是,如果我用 null object 初始化
o
的值,一切正常:
const [o, setO] = useState[{}]
What am I doing wrong?我究竟做错了什么?
Hi there in onChangeField1 you are not immutably cloning the state and that could be one of the reasons for the issue.When you assign an object to another in js it gives it a reference so嗨,在 onChangeField1 中,您不是一成不变地克隆 state,这可能是问题的原因之一。当您在 js 中将 object 分配给另一个时,它会提供参考,因此
let newO=o;
It is just passing a reference它只是传递一个参考
What you should do instead is你应该做的是
let newO={...o}
This will immutably clone the state.这将不可变地克隆 state。
Let me know if you face any issues even after this,如果您在此之后遇到任何问题,请告诉我,
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.