Calling a function after rendering a component in React.js

Asked

Viewed 1,869 times

0

I’m playing an old-fashioned game in React.js that uses the Minimax algorithm to produce the AI moves. This algorithm, from what I’ve seen, is taking between 600ms ~ 1000ms to return a play in the early stages of the game. This time would not be a problem if it were not for the fact that I am unable to make the AI move happen after the Handler click that occurs when the human player clicks a square to make his move. Resulting in the user clicking on the square and the browser "locking" until the algorithm is finished.

Board js.

class Board extends React.Component{
    constructor(props){
      super(props);
      this.state ={
        whosTurn: this.props.playerSymbol,
        gameState: new GameState(Array(9).fill(null))
      }
    }

    handleSquareClick(index){
      let board = this.state.gameState.board;

      if(board[index] === null){
        board[index] = this.state.whosTurn;
        this.setState({
          whosTurn: Math.abs(this.state.whosTurn - 1),
          gameState: new GameState(board)
        });
      }
    }

    componentDidUpdate(prevProps, prevState){
      if(this.state.whosTurn !== this.props.playerSymbol){
        // Aqui é a função que "trava" minha execução
        let newGameState = this.state.gameState.minimax();
        this.setState({
          gameState: newGameState
        });
      }
    }

    render(){
      // Renderiza o jogo de acordo com o this.state.gameState
    }
}

I don’t know much about React yet, but from what I read in the documentation, the method componentDidUpdate() comes after the render() in the life cycle of the component, therefore, the human player click should not have already been rendered?

A +/- visual example:

Turn of the human player

Vez do jogador humano

When it clicks, a for-loop is triggered to simulate the thinking algorithm. Note that its symbol has not been rendered yet

Thinking

At the end of the loop the symbol is finally rendered. And comes that Warning for free yet

Done

I appreciate any help I can get.

  • Can you put the code you have here: https://jsfiddle.net/1ve7gc8e/ ? I don’t think it’s a good idea for you to use componentDidUpdate to make new algorithm call. A callback of the setState, but with a jsFidddle it would be better to understand how you have it now.

  • Hello Mister, I’m having a hard time getting this jsFiddle that you passed, but here is the project repository. I will search this from callback in setState, and will apply. Thank you

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.