我试图仅更新对象的名字、姓氏和个人资料,而不破坏该对象内的任何其他数据...
这是当前状态的示例。
state = {
children: [
{
id: 1,
firstName: 'Bella',
lastName: 'Laupama',
profile: 'child_care',
schedules: [
{
id: 1,
date: '25 December, 2018',
parent: 'Chris',
activity: 'Christmas'
},
{
id: 2,
date: '28 December, 2018',
parent: 'Mischa',
activity: 'Christmas with Malane Whanau'
},
{
id: 3,
date: '31 December, 2018',
parent: 'Laura',
activity: 'New Years Eve'
},
{
id: 4,
date: '1 January, 2019',
parent: 'Laura',
activity: 'New Years Day'
}
]
}
]
}
这是我试图传递它来更新当前状态的当前函数...
editChild = (first, last, prof) => {
var updatedChild = {
firstName: first,
lastName: last,
profile: prof
}
var children = this.state.children
for (var i = 0; i < children.length; i++) {
if (children[i].firstName === first) {
children[i] = updatedChild
}
}
this.setState({ children })
}
**UPDATE**
Here's the code where I'm calling the function ( from a child component )
export default class EditChild extends React.Component {
state = {
firstName: '',
lastName: '',
profile: '',
}
handleChange = e => {
this.setState({
[e.target.name]: e.target.value
})
}
submitHandler = e => {
e.preventDefault()
this.props.editChild(this.state.firstName, this.state.lastName, this.state.profile)
// Final validation before submitting to server
console.log('SUBMITTED:', this.state)
// Clear the state to clear the form
this.setState({
firstName: '',
lastName: '',
profile: ''
})
}
...表单等在渲染等中...
表单工作正常,控制台记录结果如下:
SUBMITTED:
{firstName: "Donald", lastName: "Trump", profile: "face"}
更新
感谢@Tholle 和@charlietfl 引领我走向正确的方向。基本上,我还需要传递 ID,而不是尝试根据名字进行匹配,因为名字显然也可以从编辑表单中更改。因此,如果我将 Bella Laupama 更改为 Charlie Chaplan,它就找不到 id。
所以我使用了 @Tholle 代码并将其修改为通过 id 进行搜索和替换,效果非常好:)
editChild = (id, first, last, prof) => {
var updatedChild = {
firstName: first,
lastName: last,
profile: prof
}
this.setState(prevState => {
const children = [...prevState.children]
const childIndex = children.findIndex(child => child.id === id)
children[childIndex] = { ...children[childIndex], ...updatedChild }
return { children }
})
console.log(this.state)
}
最佳答案
您可以通过 findIndex
获取子项的索引然后将新数组中具有该索引的对象替换为原始对象的副本,并添加了 updatedChild
中的所有属性。
示例
class App extends React.Component {
state = {
children: [
{
id: 1,
firstName: "Bella",
lastName: "Laupama",
profile: "child_care",
schedules: [
{
id: 1,
date: "25 December, 2018",
parent: "Chris",
activity: "Christmas"
},
{
id: 2,
date: "28 December, 2018",
parent: "Mischa",
activity: "Christmas with Malane Whanau"
},
{
id: 3,
date: "31 December, 2018",
parent: "Laura",
activity: "New Years Eve"
},
{
id: 4,
date: "1 January, 2019",
parent: "Laura",
activity: "New Years Day"
}
]
}
]
};
editChild = (first, last, prof) => {
var updatedChild = {
firstName: first,
lastName: last,
profile: prof
};
this.setState(prevState => {
const children = [...prevState.children];
const childIndex = children.findIndex(child => child.firstName === first);
children[childIndex] = { ...children[childIndex], ...updatedChild };
return { children };
});
};
render() {
return (
<div>
<div>{JSON.stringify(this.state)}</div>
<button onClick={() => this.editChild("Bella", "Doe", "Programmer")}>
Edit child
</button>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
关于javascript - 如何编辑/更新数组中的对象并保留所有其他嵌套数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53421713/