英文:
Updating state data containing a nested array of objects
问题
我的状态数据" data "包括以下嵌套对象数组
{
"message": "成功获取电影。",
"films": [
{
"_id": "640685ea5d0f00f7f2e4c5b5",
"title": "猫女:猎物",
"imageUrl": "images/5.png",
"releaseDate": "2023-03-16T04:00:00.000Z",
"reviewcnt": 4,
"reviewavg": 3,
"userlikecnt": 3
},
{
"_id": "640685f05d0f00f7f2e4c5bf",
"title": "巨魔",
"imageUrl": "images/1.jpg",
"releaseDate": "2023-01-23T04:00:00.000Z",
}
]
}
我试图按如下方式减少 filmID: 640685ea5d0f00f7f2e4c5b5 的 userlikecnt:
setData(prevState => {
prevState.films.map(film => {
if (film._id === id)
return {
...film,
userlikecnt: film.userlikecnt - 1,
}
return film;
})
})
其中 id 包含 "640685ea5d0f00f7f2e4c5b5"。上述代码不起作用。
英文:
My state "data" consist of the following nested array of objects
{
"message": "Fetched films successfully.",
"films": [
{
"_id": "640685ea5d0f00f7f2e4c5b5",
"title": "Catwoman: Hunted",
"imageUrl": "images/5.png",
"releaseDate": "2023-03-16T04:00:00.000Z",
"reviewcnt": 4,
"reviewavg": 3,
"userlikecnt": 3
},
{
"_id": "640685f05d0f00f7f2e4c5bf",
"title": "Troll",
"imageUrl": "images/1.jpg",
"releaseDate": "2023-01-23T04:00:00.000Z",
I'm trying to decrement the userlikecnt of filmID : 640685ea5d0f00f7f2e4c5b5 as follows:
setData(prevState=>{
prevState.films.map(film=>{
if(film._id===id)
return{
...film,
userlikecnt:film.userlikecnt-1,
}
return film;
})
})
Where id containts "640685ea5d0f00f7f2e4c5b5". The above code isn't working
答案1
得分: 1
看起来你没有在映射films数组后返回修改后的状态。你可以修改你的代码:
setData(prevState => {
return {
...prevState,
films: prevState.films.map(film => {
if (film._id === id) {
return {
...film,
userlikecnt: film.userlikecnt - 1
};
}
return film;
})
};
});
英文:
It looks like you are not returning the modified state after mapping over the films array. You can modify your code:
setData(prevState => {
return {
...prevState,
films: prevState.films.map(film => {
if (film._id === id) {
return {
...film,
userlikecnt: film.userlikecnt - 1
};
}
return film;
})
};
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论