首页 文章

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

提问于
浏览
3

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

false为true或null为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>
    )
  }
}

3 回答

  • 8

    将setTimeout调用移到 componentDidMount 内部并在其中使用 this.setState

  • 9

    你必须使用 this.setState({newForm: true}) 而不是 this.state = {newForm : true}

    并将 setState 放在other lifecycle stages中 .

  • -2

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

相关问题