繁体   English   中英

我如何在React状态下更新数组内部的对象属性的值

[英]How do I update the value of an object property inside of an array in React state

我似乎在这里找不到与这种情况相关的答案。

我在React组件中有状态:

this.state = {
    clubs: [
       {
           teamId: null,
           teamName: null,
           teamCrest: null,
           gamesPlayed: []
        }
    ]
}

我通过API请求接收到一些数据,并且仅更新了部分状态,如下所示:

this.setState((currentState) => {
    return {
        clubs: currentState.clubs.concat([{
            teamId: team.id,
            teamName: team.shortName,
            teamCrest: team.crestUrl
        }]),
    }
});

稍后,我想修改属性值之一的状态值-gamesPlayed值。

我该怎么做呢? 如果我使用与上面相同的方法,它只会向数组中添加额外的对象,因此我似乎无法针对该特定对象属性。 我的目标是维护clubs数组中的对象,但修改gamesPlayed属性。

本质上,我想做类似的事情:

clubs: currentState.clubs[ index ].gamesPlayed = 'something';

但这不起作用,我不确定为什么。

因为您正在使用concat()函数,该函数会在数组中添加新项。

您可以使用findIndex在对象数组中查找索引,并根据需要替换它:

解:

 this.setState((currentState) => {
    var foundIndex = currentState.clubs.findIndex(x => x.id == team.id);
    currentState.clubs[foundIndex] = team;

    return clubs: currentState.clubs
});

我会更改您的状态的结构。 由于teamId在数组中是唯一的,因此我将其更改为对象。

clubs = {
  teamId: {
    teamName,
    teamCrest,
    gamesPlayed
  }
}

然后,您可以像这样更新状态:

addClub(team) {
    this.setState(prevState => ({
      clubs: {
        [team.id]: {
          teamName: team.shortName,
          teamCrest: teamCrestUrl
        },
        ...prevState.clubs
      }
    }));
  }

  updateClub(teamId, gamesPlayed) {
    this.setState(prevState => ({
      clubs: {
        [teamId]: {
          ...prevState.clubs[teamId],
          gamesPlayed: gamesPlayed
        },
        ...prevState.clubs
      }
    }));
  }

这样避免了为团队find数组的麻烦。 您可以从对象中选择它。

您可以根据需要将其转换回数组,如下所示:

Object.keys(clubs).map(key => ({
  teamId: key,
  ...teams[key]
  }))

我采用的方法是JSON.parse && JSON.stringify以制作要更改的状态部分的深层副本,使用该副本进行更改,然后从那里更新状态。

使用JSON的唯一缺点是,请不要记住复制函数和引用。

对于您的示例,要修改gamesPlayed属性:

let newClubs = JSON.parse(JSON.stringify(this.state.clubs))

newClubs.find(x => x.id === team.id).gamesPlayed.concat([gamesPlayedData])

this.setState({clubs: newClubs})

我假设您想每次从您的API中添加新的gamesPlayedData ,并在其中获得team.id和该数据。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM