更新包含嵌套对象数组的状态数据

huangapple go评论137阅读模式
英文:

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;
    })
  };
});

huangapple
  • 本文由 发表于 2023年3月8日 19:28:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75672435.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定