gpt4 book ai didi

javascript - 如何编辑/更新数组中的对象并保留所有其他嵌套数据?

转载 作者:行者123 更新时间:2023-11-29 20:48:11 25 4
gpt4 key购买 nike

我试图只更新一个对象的名字、姓氏和个人资料,而不破坏该对象中的任何其他数据...

这是当前状态的示例。

  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 获取 child 的索引然后用原始对象的副本替换新数组中具有该索引的对象,并添加了 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com