从动态创建的子组件更改状态-React

时间:2019-12-13 16:44:35

标签: javascript reactjs state dom-events setstate

在此应用中,您可以通过单击特定游戏的o按钮来更改足球比赛得分。问题是我的匹配项保存在状态中,并且我使用GOAL方法进行渲染,因此我不能为每个匹配项动态使用setState。

App.js

map

Match.js

import React from 'react';

import Match from './components/Match';

import './App.css';

export default class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      games: [
        {
          home: {
            team: "Bruges",
            score: 0
          },
          guests: {
            team: "Real Madrid",
            score: 0
          }
        },
        {
          home: {
            team: "Atletico Madrid",
            score: 0
          },
          guests: {
            team: "Lokomotiv",
            score: 0
          }
        }
      ]
    };

    this.goal = this.goal.bind(this);
  };

  goal(parent) {
    let rand = Math.round(Math.random());

    if(rand) {
      this.setState((prevstate) => ({parent:  prevstate.parent.home.score + 1}))
    } else {
      this.setState((prevstate) => ({parent: prevstate.parent.guests.score + 1}))
    }
  }

  render() {
    return (
      <div className="App">
        {this.state.games.map((item, index) => {
          return (<Match 
            key={index}

            home={item.home.team}
            homeScore={item.home.score}

            guests={item.guests.team}       
            guestsScore={item.guests.score}

            goal={() => this.goal(item)}
          />);
        })}
      </div>
    );
  }

}

CodeSandBox

我认为我的问题出在import React from 'react'; import '../App.css' const Match = props => { return( <div className="match-container"> <span className="name-container">{props.home} </span> <span className="score-container">{props.homeScore}</span> <button onClick={props.goal}>GOAL</button> <span className="score-container">{props.guestsScore} </span> <span className="name-container">{props.guests} </span> </div> ); } export default Match; 方法中,因为我认为我不能传递参数并在goal中使用它。

我没有找到与此特定问题相关的答案。

1 个答案:

答案 0 :(得分:1)

问题是您试图像将其作为对象一样更新数组。事实是您已将游戏设置为状态数组。更新方法如下:

goal(parent) {
    let rand = Math.round(Math.random());
    const { games } = this.state;
    const index = games.findIndex(element => element === parent);
    const newGames = [...games];
    if (rand) {
      newGames[index].home.score = newGames[index].home.score + 1;
    } else {
      newGames[index].guests.score = newGames[index].guests.score + 1;
    }
    this.setState({ games: newGames });
  }

这是一个正在运行的演示https://codesandbox.io/s/practical-margulis-n0ch1