渲染方法被调用两次

时间:2020-04-04 15:39:39

标签: javascript reactjs

我是React的新手,现在我关注react tutorial,它制作了一个井字游戏。我也在尝试遵循。我的问题是render方法被调用了两次,我不知道为什么。

主板组件

 export class Board extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      squares: Array(9).fill(null),
      Xturn: true,
    };
  }

  changeTurn(i) {
    const squares = this.state.squares.slice();
    if (this.calculateWinner(squares)) {
      return;
    } else {
      squares[i] = this.state.Xturn ? "X" : "Y";
      this.setState({
        squares: squares,
        Xturn: !this.state.Xturn,
      });
    }
  }

  calculateWinner(squares) {
    const lines = [
      [0, 1, 2],
      [3, 4, 5],
      [6, 7, 8],
      [0, 3, 6],
      [1, 4, 7],
      [2, 5, 8],
      [0, 4, 8],
      [2, 4, 6],
    ];

    for (let i = 0; i < lines.length; i++) {
      const [a, b, c] = lines[i];
      if (squares[a] === squares[b] && squares[a] === squares[c]) {
        return squares[a];
      }
    }
    return null;
  }

  createTable(rows) {
    let table = [];
    let child_key = 0;
    for (let i = 0; i < rows; i++) {
      let children = [];

      for (let j = 0; j < rows; j++) {
        children.push(
          <Square
            key={child_key}
            indicator={child_key}
            value={this.state.squares[child_key]}
            handleClick={(d) => this.changeTurn(d)}
          />
        );
        child_key++;
      }

      table.push(<div className="board-row">{children}</div>);
    }
    return table;
  }

  render() {
    console.log("render");
    const winner = this.calculateWinner(this.state.squares);
    if (winner) {
      console.log("done");
      alert("we have a winner");
    }
    return <div className="board">{this.createTable(3)}</div>;
  }
}

它是平方分量

 export class Square extends React.Component {
  constructor(props) {
    super(props);
  }

  OnClick = () => {
    this.props.handleClick(this.props.indicator);
  };

  render() {
    return (
      <div className="square" onClick={this.OnClick}>
        {this.props.value}
      </div>
    );
  }
}

当一个玩家连续三个(获胜)时,为什么我会收到两个警报(我们有一个获胜者)?

这就是我在控制台

中看到的内容
render
done
render
done

为什么React两次调用render()?

1 个答案:

答案 0 :(得分:0)

这是默认行为。您可以参考https://reactjs.org/docs/react-component.html了解生命周期方法。基本上,首先加载构造函数,然后加载render方法。要详细说明,您还可以查看此答案-Why is render() being called twice in ReactNative?。在您的情况下,首先调用初始值,然后进行setState。如果您不想显示任何东西,请使用条件。

相关问题