2015-08-26 23 views
3

我点击按钮时渲染一个新窗体。所以基本上我从组件中更改状态:在状态变化时不响应重新渲染

假为真或 空真

然而,令人奇怪的状态改变后,该组件没有重新渲染

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

回答

7

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

而且在other lifecycle stagessetState

+0

我觉得在ES6 this.state基本上是this.setState –

+5

'this.state ='是不一样'this.setState'。 – Taysky

+1

@max_new ES6与这些React特定的方法调用无关。 –

8

移动setTimeout调用到componentDidMount内使用this.setState在那里

+0

谢谢@Samer。最后的解决方案,这是工作 –

+1

@max_new这是堆栈溢出接受(即“检查”),无论哪个答案实际上回答你的问题的良好做法。 – machineghost

相关问题