gpt4 book ai didi

javascript - 替换状态数组中的项目

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

我已经研究了一段时间如何替换状态数组中已经存在的项目,但我找不到合适的解决方案
https://codesandbox.io/s/4xl24j7r69

import React from 'react';


class App extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [
{
"userId": 1,
"id": 1,
"title": "One",
"body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
},
{
"userId": 1,
"id": 2,
"title": "Two",
"body": "est rerum tempore vitae\nsequi sint nihil reprehenderit dolor beatae ea dolores neque\nfugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\nqui aperiam non debitis possimus qui neque nisi nulla"
},
]
}
}

add = () => {
this.setState(prevState => ({

data: [...prevState.data,
{
"userId": 1,
"id": 2,
"title": "Two New",
"body": "new data",
}// this item already exist so I want to replace it to new data
]
}))
};
render() {
return (
<div>
{this.state.data.map((data) =>
<ul key={data.id}>
<li>{data.title}</li>
</ul>
)}
<button onClick={this.add}>Replace</button>
</div>
);
}
}
export default App;

我试过了,但是不行

 add = () => {
this.setState(prevState => ({
data: prevState.data.filter(item => this.state.data.indexOf(item.id) !== -1).slice(0, 5), // this not working
data: [...prevState.data,
{
"userId": 1,
"id": 2,
"title": "Two New",
"body": "new data"
}
]
}))
};

如果项目已经存在,我该如何更新?

最佳答案

您可以找到该项目并使用 object.assign 简单地更新它

let newUser1 = {
"userId": 1,
"id": 2,
"title": "Two New",
"body": "new data"
}

this.setState(prevState => {
let newData = prevState.data;
let user = newData.find(d => d.id === newUser1.id);
Object.assign(user, newUser1);
return {data: newData};
})

关于javascript - 替换状态数组中的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49309761/

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