使用模板文字在没有 eval() 的情况下动态地将值添加到 React 中的 setState

Using template literal to dynamically add values to setState in React without eval()

我是 React 的新手,正在尝试创建一个具有以下状态的记分牌应用程序:

state = {
    home_team: [
      {
        id: 1,
        name: "Jobe Watson",
        goals: 0,
        behinds: 0,
      },
      {
        id: 2,
        name: "James Hird",
        goals: 0,
        behinds: 0,
      },
      {
        id: 3,
        name: "Steven Alessio",
        goals: 0,
        behinds: 0,
      },
      {
        id: 4,
        name: "Che Cockatoo-Collins",
        goals: 0,
        behinds: 0,
      }
    ],
    away_team: [
      {
        id: 1,
        name: "Chris Judd",
        goals: 0,
        behinds: 0,
      },
      {
        id: 2,
        name: "Anthony Koudafidis",
        goals: 0,
        behinds: 0,
      },
      {
        id: 3,
        name: "Steven Silvagni",
        goals: 0,
        behinds: 0,
      },
      {
        id: 4,
        name: "Brendan Fevola",
        goals: 0,
        behinds: 0,
      },
    ]
  }

我正在尝试 运行 如下所示的分数更改功能:

addScore = (i, delta, team, score) => {
    const val = eval(`this.state.${team}[${i}].${score} += ${delta}`)
    console.log(val)
    this.setState( {
        [score]: val
    })
  }

在Counter组件中调用的地方如下:

onClick={()=>addScore(index, +1, team, 'goals')

在这种情况下,"index" 指的是任一球队数组中的球员索引,"team" 指的是 "home_team" 或 "away_team"。

我似乎能够将信息动态添加到 setState 方法中的唯一方法似乎是通过模板文字进入 eval(),然后在 setState 中调用它。

知道 eval() 存在问题 - 还有其他方法可以做到这一点吗?我尝试使用 new Function()() 但没有成功。

谁能提供另一种解决方案?提前致谢。

我认为您对如何通过所有可用变量获取访问值有点困惑,在这里您可以使用简单的方法:

// this.state.${team}[${i}].${score}

this.state[team][i][score]

其次你正在改变状态,你不应该,你可以这样更新状态:

addScore = (i, delta, team, score) => {
    const updated = this.state[team].map((el,index) => {
        if(i=== index) {
            const score = el.score + delta;
            el = { ...el , score }
        }
        return el
    })

    this.setState((state) => {
        ...state ,
        [team] : updated
    })
}