Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React not re-rendering on state change

Tags:

reactjs

I am rendering a new form when the button is clicked. So basically I change a state within the component from:

false to true or null to true

However, it is strange that component does not re-render after the state change

export default class BoardManager extends React.Component{
   constructor(){
    super();
    this.state = {
      newForm : null
    };
    setTimeout(() => {
      this.state = {
        newForm : true
      };
      console.log(this.state.newForm);
    },1000);
  }

  render(){
    return(
      <div>
        Some thing here
        {this.state.newForm ? <NewBoardForm />: null}
      </div>
    )
  }
} 

Help much appreciated!!!

Edit!!! Solution

export default class BoardManager extends React.Component{
  constructor(){
    super();
    this.state = {
      newForm : null
    };
  }

  render(){
    return(
      <div>
        <BoardsTable boards={BoardData.boards}/>
        <button onClick={() => {
            this.setState({
              newForm : true
            });
            console.log(this.state.newForm);
          }}>Add New</button>
          <button onClick={() => {
              this.setState({
                newForm : null
              });
              console.log(this.state.newForm);
            }}>Delete</button>
        {this.state.newForm ? <NewBoardForm />: null}
      </div>
    )
  }
}
like image 407
max_new Avatar asked Aug 26 '15 16:08

max_new


2 Answers

Move the setTimeout call to inside a componentDidMount and use this.setState in there

like image 69
Samer Buna Avatar answered Sep 27 '22 18:09

Samer Buna


You have to use this.setState({newForm: true}) instead of this.state = {newForm : true}

And put setState in other lifecycle stages.

like image 28
zachguo Avatar answered Sep 27 '22 17:09

zachguo