亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

為什么我的輸入 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 關注
  • 176 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號