猿问

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

我正在构建一个用户流程,以允许用户输入他们玩过的视频游戏的统计数据。我的 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 函数中呈现输入有关,但我尝试分离测试输入,结果是相同的。任何帮助表示赞赏!


慕妹3146593
浏览 153回答 2
2回答

哔哔one

假设您有 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)                }            });
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答