为了账号安全,请及时绑定邮箱和手机立即绑定

为什么我的输入 onChange 事件会更改对象数组中的多个状态值?

为什么我的输入 onChange 事件会更改对象数组中的多个状态值?

慕妹3146593 2021-10-29 14:55:32
我正在构建一个用户流程,以允许用户输入他们玩过的视频游戏的统计数据。我的 react 组件呈现了一个类似于表格的 excel,他们可以在其中手动输入统计数据(就像一个 excel 电子表格,其中 y 轴是一列球员,x 轴是每个球员的统计数据。当我更新特定玩家的特定统计数据时,每个玩家对该特定统计数据的统计值也会发生变化。例如,如果我将球员 A 更新为 5 个进球,则团队中的每个其他球员也将有 5 个进球。这不应该发生。首先,我初始化一个 matchStats 对象:initializeMatchStats = (numGames) => {    const {matchInfo} = this.props;    const gameArray = new Array(numGames).fill('');    const matchStats = gameArray.map((game, i) => {        let statsWithKeys = {};        let gameInfo = {};        matchInfo.circuitStats.map(key => {            statsWithKeys[key.toLowerCase()] = 0        })            const players = new Array(matchInfo.playersAllowedInGame).fill({                stats: statsWithKeys            }).map(p => {                return {                    ...p,                    dropdownOpen: false,                    id: Math.random().toString(36)                }            })            gameInfo = {                players,                index: i + 1            }        return gameInfo    })    this.setState({matchStats, numGames, numGamesModalOpen: false, uploadManually: true}, () => console.log('matchStats: ', matchStats))}然后,我更新 matchStats 对象,因为它被用户更改:updateStatsManually = (val, player, game, header, e) => {        e.preventDefault();        const {matchStats} = this.state;        // matchStats is an array of games in each match. A game is made up of the players (and their respective stats) in the game.        const { matchInfo } = this.props;        const gameToUpdate = matchStats.find(g => g.index === game.index)我希望当我更改给定玩家的一项统计数据的输入值时,它只会更改该特定玩家的统计数据。但是,它会为每个玩家改变它。我已经搞砸了一段时间,并努力找出我做错了什么。我认为这可能与如何在 .map 函数中呈现输入有关,但我尝试分离测试输入,结果是相同的。任何帮助表示赞赏!
查看完整描述

2 回答

?
哔哔one

TA贡献1854条经验 获得超8个赞

假设您有 5 名玩家的限制。在这种情况下,这个:


         const players = new Array(matchInfo.playersAllowedInGame).fill().map(p => {

                return {

                   stats: statsWithKeys,

                   dropdownOpen: false,

                   id: Math.random().toString(36)

                }

            })

没有像您期望的那样创建 5 个 'statsWithKeys',而是 5 个对相同 'statsWithKeys' 的引用。


解决此问题的最佳方法是直接在对象本身上使用扩展运算符:


         const players = new Array(matchInfo.playersAllowedInGame).fill().map(p => {

                return {

                   stats: { ...statsWithKeys },

                   dropdownOpen: false,

                   id: Math.random().toString(36)

                }

            });


查看完整回答
反对 回复 2021-10-29
  • 2 回答
  • 0 关注
  • 152 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信