我有一个更新表单来更新用户的信息。
const { basic: userBasic } = this.state.user;
<Modal open={openEditBasicModal} size="small">
<Modal.Header>Your basic details</Modal.Header>
<Modal.Content scrolling>
<Form>
<Form.Group inline widths="equal">
<Form.Input
fluid
type="text"
name="firstName"
defaultValue={userBasic.firstName}
onChange={this.handleBasicFromInputValue}
label="First Name"
/>
<Form.Input
fluid
type="text"
name="lastName"
defaultValue={userBasic.lastName}
onChange={this.handleBasicFromInputValue}
label="Last Name"
/>
</Form.Group>
</Form>
</Modal.Content>
<Modal.Actions open={true}>
<Button
primary
onClick={this.updateUserBasicInfo}>
Update
</Button>
</Modal.Actions>
</Modal>
组件的状态是:
this.state = {
user: {
basic: {
firstName: null,
lastName: null,
email: null
},
//others
}
}
表单中的默认值来自state
,逻辑是通过在表单字段上使用onChange
处理程序来更新state
。所以我为此使用了一个简单的处理程序:
handleBasicFromInputValue = event => {
this.setState({
user: {
basic: {
[event.target.name]: event.target.value
}
}
});
};
上面的处理程序DID更新了状态,但是它还删除了组件中声明的state
架构。如果用户状态有
user: {
basic: {
firstName: "theCoder",
lastName: "lastCoder",
email: "something@gmail"
}
}
现在我更新了表单中的 firstName
字段,状态更改为
user: {
basic: {
firstName: "theCoderUpdated",
}
}
如果我现在在表单提交上打印用户状态:
updateUserBasicInfo = () => {
console.log(this.state.user.basic);
}
它只打印包含 firstName: "theCoderUpdated"
所有其他状态变量都消失了。其他状态变量不应该保持不变吗?
我认为这是导致问题的 [event.target.name]
,但我不确定原因。
[event.target.name]
在幕后如何工作?进行此状态更改的正确方法是什么?
最佳答案
React 只进行浅层状态合并。您可以在这里阅读:
https://reactjs.org/docs/state-and-lifecycle.html#state-updates-are-merged
这意味着当您调用setState
时,所有顶级属性都将被完全替换。对于您来说,这意味着 user
完全替换为您通过 setState
发送的新用户对象。您可以通过两种方式解决这个问题。您可以展平您的状态对象,并在您的状态中拥有 firstName
、lastName
、email
,如下所示:
this.state = {
firstName: null,
lastName: null,
email: null
}
或者你必须像这样更新你的状态:
handleBasicFromInputValue = event => {
this.setState({
user: {
basic: {
...this.state.user.basic,
[event.target.name]: event.target.value
}
}
});
};
关于javascript - React 组件的状态如何通过使用 [event.target.name] 来改变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55687231/