React JS-onClick在setState中的对象内创建对象

时间:2018-09-28 10:05:08

标签: javascript reactjs onclick setstate

我正在为乒乓球比赛制作一个React应用程序。下面的代码。

import React, { Fragment, Component } from "react";
import Button from "./Button";

const playerStylingTrue = {
    backgroundColor: "#26C281"
   };

class Matches extends Component {
     constructor(props) {
     super(props);
     this.state = {
          numOfRounds: "",
          numberOfPlayers: this.props.numberOfPlayers,
          player1Clicked: false,
          player2Clicked: false,
          winners: []
          }

this.onClickWinnerP1 = this.onClickWinnerP1.bind(this);
this.onClickWinnerP2 = this.onClickWinnerP2.bind(this);
}

numberOfRounds() {
  const { numberOfPlayers } = this.state;
  const numOfRounds = Math.ceil((Math.log(numberOfPlayers)) / 
   (Math.log(2)));
  this.setState = ({
      numOfRounds: numOfRounds
      })
 };

onClickWinnerP1(player1) {
let player1String = player1.toString()
let { winners } = this.state;
// let findWinner = winners.find(o => o.player1String === player1);
//winners.includes(findWinner) ? null : 

  this.setState({
    player1Clicked: !this.state.player1Clicked,
    player2Clicked: this.state.player1Clicked,
    winners: [{...winners, player1String, winner:true}]
  })
};

onClickWinnerP2(player2) {
  let player2String = player2.toString()
  let { winners } = this.state;
  this.setState({
    player2Clicked: !this.state.player2Clicked,
    player1Clicked: this.state.player2Clicked,
    winners: winners.includes(player2String) ? [...winners] : 
[{...winners, player2String, winner:true}]
  })

};

 render() {
  const { pairs } = this.props;
  const { winners } = this.state;
  console.log(winners)
  return (
    <Fragment>
      <Button
        onClick={this.props.onClick}
        className={"btn btn-success"}
        buttonText={"Create Random Matches "}
      />
      {pairs.map((pair, i) => {
          let player1 = [...pair];
          let player2 = player1.splice(0, Math.ceil(player1.length / 
        2));
        return (
          <div key={i} className="fixture-div">
            <ul className="list-unstyled fixture-list">
              <li
                style={ this.state.winners.includes(player1) ? playerStylingTrue : null}
                onClick={() => this.onClickWinnerP1(player1)}
                className="hvr-grow fixture">
                {player1}
              </li>
              <span>vs</span>
              <li
                style={this.state.winners.includes(player2) ? playerStylingTrue : null}
                onClick={() => this.onClickWinnerP2(player2)}
                className="hvr-grow fixture">
              {player2}
            </li>
          </ul>
        </div>
      )
    })
    }
    {/* <TwoRounds pairs={pairs}/> */}
  </Fragment>
   );
  }
 }

 export default Matches;

当前,onClickWinnerP1已成功将对象添加到状态,其中包含正确的详细信息。但是,如果我单击两次或使用onClickWinnerP2,也会向状态添加一个对象,但是嵌套在已经存在的对象中。依此类推。只是保持嵌套。

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

在noOfRounds函数中执行setState的方式不正确。相反,您应该像下面这样

  this.setState({
     numOfRounds: numOfRounds
  })

关于您的问题,请在onClickWinnerP1函数中执行以下操作,将对象推入数组

this.setState(prevState => ({
   player1Clicked: !this.state.player1Clicked,
   player2Clicked: this.state.player1Clicked,
   winners: [...prevState.winners, {player1String, winner:true}]
}))

在onClickWinnerP2函数中进行AND操作,如下所示将对象推入数组

this.setState(prevState => ({
    player2Clicked: !this.state.player2Clicked,
    player1Clicked: this.state.player2Clicked,
    winners: prevState.winners.includes(player2String) ? [...prevState.winners] : 
[...prevState.winners, {player2String, winner:true}]
  }))