React不会在状态更改时重新呈现

时间:2015-08-26 16:05:50

标签: reactjs

单击按钮时,我正在渲染新表单。所以基本上我改变了组件中的状态:

false为true或 null to true

然而,奇怪的是,在状态改变之后组件不会重新渲染

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

非常感谢!!!

编辑!!!溶液

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

2 个答案:

答案 0 :(得分:8)

您必须使用this.setState({newForm: true})代替this.state = {newForm : true}

并将setState放入other lifecycle stages

答案 1 :(得分:-2)

您可以在onClick结束时使用this.forceUpdate()。 参考: https://facebook.github.io/react/docs/component-api.html

相关问题