2017-05-24 18 views
0

我有一個組件有2個孩子。爲什麼ReactJs在局部狀態改變時繪製整個組件?

React.createClass({ 
    getInitialState: function(){ 
     return {ch_1 : 'Child 1', ch_2: 'child_2'}; 
    }, 
    _onChange : function(e){ 
     var value = e.target.value; 
     var id = e.target.id; 
     if(id == '1'){ 
      this.setState({ch_1 : value}); 
     } 
     else{ 
      this.setState({ch_2 : value}); 
     }; 
    }, 
    Render : function(){ 
     return React.createElement('div', {key: 10000 }, 
     React.createElement('input', {id: '1', key: 10, value: this.state.ch_1, 
      onChange: this._onChange}), 
     React.createElement('input', {id: '2', key: 20, value: this.state.ch_2, 
      onChange: this._onChange})) 
    } 
}); 

當一個局部狀態改變時,整個組件再次被繪製。問題在於,在我的項目中,我有很多孩子,重繪整個組件會讓我的項目太慢。因爲我必須等待所有的組件被更新(我正在談論大約2百個孩子)。

任何人都可以告訴我爲什麼它的工作原理是這樣的嗎?

謝謝

+0

可能重複https://stackoverflow.com/questions/33613728/what-happens-when-using-this-setstate-multiple-times-in-react-component – oklas

+0

你可以使用'shouldComponentUpdate(nextProps,nextState)'來確定組件是否應該重新渲染。 https://facebook.github.io/react/docs/react-component.html#shouldcomponentupdate – Akeel

回答

0

的組件中的狀態變化會導致整個組件,並在它的子組件的重新渲染。爲了優化它,您可以使用生命週期方法shouldComponentUpdate,如此處所述。 https://facebook.github.io/react/docs/react-component.html#shouldcomponentupdate

在shouldComponentUpdate方法中,您可以根據自己的檢查重新呈現組件。

因此,會發生什麼情況是,如果組件的道具或狀態沒有改變,組件將不會不經意地重新渲染。

1

其實我已經用這種方法解決了。如果元素的狀態發生變化或者具有不同的鍵,React會重新呈現該元素。所以我實現了一個爲每個元素返回一個唯一的函數。

React.createClass({ 
    customData: { 
     keys: {} 
    }, 
    getKey : function(path/*can be div-root-object-attribute-*/ , 
     elementName /*I use className*/){ 

     var numberSeparator = '###'; 
     var keyPrefix = 'key_' + path.replace(/ /g,'_') + '_' + 
       elementName.replace(/ /g,'_') + numberSeparator; 

     var newNumber = this.customData.keys[keyPrefix] != null ? 
       this.customData.keys[keyPrefix] + 1 : 1; 
     newKey = keyPrefix + newNumber; 
     this.customData.keys[keyPrefix] = newNumber; 

     return newKey; 
    }, 
    render : function(){ 
      //important => so it will try to render again with the same 
      //keys and will skip element with unchanged state 
      this.customData.keys = {}; 
      return React.createElement(); 
    } 

})

相關問題