2015-10-19 93 views
0

這是我的組件的結構:如何在數據更新後重新呈現Reactjs組件?

module.exports = React.createClass({ 

    getInitialState(){ 
     data = .... //by connecting to a db server 

     var properties = fun(...) //other functions manipulating the data 

     return { 

      data:data, 
      .... //other UI functions 

     } 

    onSearch(e){ 
      e.preventDefault(); 
      var startdate = React.findDOMNode(this.ref.start).value; 

      //******** here I want to update the data in the view using this new startdate 
      //so essentially I just want to replace "data = " in the getInitialState() bcoz I 
      //want other data manipulation functions from getInitialState to run as well.  
     } 

    render(){ 

     return(
      <form className = "dateform" onSubmit = {this.onSearch}> 
       <input type = "text" ref = "start" /> 
      </form> 

      ... 

      //other UI return stuff 
     ) 
    } 
)} 

我應該如何去這樣做// *******?

我想只更新getInitialState()中的數據變量,這取決於我在表單域中獲得的日期。隨後使用新數據刷新視圖。我應該在onSearch函數中做什麼改變?

這是一個正確的方法嗎?

onSearch() 
{ 
    data = //make $.ajax call to get new data 
    this.setState({ 
     data: data 
    }); 

} 
+0

[按鈕,單擊更改組件的狀態(的可能的複製https://stackoverflow.com/questions/36183304/change-component-state-on-button - 點擊) –

回答

3

看看狀態in documentation here。您可以通過調用的setState方法類似這樣的改變:

onSearch (e) { 
    // get somehow new data 

    this.setState({ 
     data: newData 
    }); 
} 
相關問題