簡體   English   中英

渲染方法被調用兩次

[英]Render method is called twice

我對 React 完全陌生,現在我正在關注制作井字游戲的 React教程 我也在努力追隨它。 我遇到的問題是渲染方法被調用了兩次,我不知道為什么。

板組件

 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>;
  }
}

它是Square 組件

 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() 兩次?

這是默認行為。 生命周期方法可以參考https://reactjs.org/docs/react-component.html 基本上,首先加載構造函數,然后加載渲染方法。 詳細說明一下,您還可以查看這個答案 - 為什么在 ReactNative 中調用了兩次 render()? . 在您的情況下,首先調用初始值,然后發生 setState。 如果您不想顯示某些內容,請使用條件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM