2015-08-26 101 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

相關問題