reactjs - React 不会在状态改变时重新渲染

标签 reactjs

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

从假到真或 空到真

但是,奇怪的是,状态改变后组件没有重新渲染

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

最佳答案

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

关于reactjs - React 不会在状态改变时重新渲染,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32231513/

相关文章:

node.js - 服务器未向前端发送正确的响应?

reactjs - 为什么在 React 中返回时需要额外的包装器?

reactjs - 如何正确处理react-router中的子路由(路由有效,但URL随着每次点击而增长)

reactjs - 有没有办法访问 React 组件的子组件?

javascript - 上述错误发生在<Provider>组件中

reactjs - 一个屏幕上带有过滤器的多个 React Admin 列表

javascript - React Native 底部选项卡导航不起作用

javascript - 访问对象内部的属性

javascript - 将jsPDF生成的PDF发送到服务器

javascript - 如何使用 React 或 Angular 创建仅在需要时加载的可重用画廊