【发布时间】:2018-09-08 20:54:44
【问题描述】:
我需要更新状态中的对象,但只更新它的一些元素。因此,如果它有 7 个元素,而我的新对象有 4 个,那么这 4 个应该替换现有的,而其余的应该保留。
这是一个示例组件,它输出状态中的当前对象键和值。当您按下按钮时,该对象应该会使用其某些属性的新值进行更新。现在它正在用 4 个元素覆盖对象,所以我需要修改它。参见 handleClick 方法。
在我的真实项目中,对象处于 redux 状态,但我想解决方案是一样的。我从发布的表单中获取新属性,因此我有一个类似于下面名为“update”的对象。
import React, { Component } from 'react';
import Button from 'material-ui-next/Button';
import Menu, { MenuItem } from 'material-ui-next/Menu';
class UpdateObject extends Component {
constructor(props) {
super(props)
this.state = {
theObject : {
token: '478478478478',
firstName: 'Goofy',
lastName: 'Hello',
age: '14',
sex: 'female',
employed: true,
favoriteColor: 'Blue',
bio: 'details of bio',
}
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
let update = {
age: '40',
lastName: 'Newname',
employed: true,
favoriteColor: 'Yellow',
}
let change = Object.assign({}, this.state.theObject);
change = update;
this.setState({ theObject: change });
}
render() {
const myObj = this.state.theObject;
return (
<div className="updateobjectwrapper bl">
<div> Here is the current object: <br />
<ul>
{ Object.entries(myObj).map(([ key,value ] ) => {
return (
<li key={key}>{key} : {value} </li>
)
})
}
</ul>
</div>
<Button
onClick={this.handleClick}
>
Update Object
</Button>
</div>
)
}
}
【问题讨论】:
标签: reactjs ecmascript-6 redux