2017-07-28 52 views
1

非常基本的代碼示例:反應重新渲染陣列,而項重點沒有改變列表

class List extends React.Component { 
    render() { 
     const listComponent = this.props.numbers.map((number) => 
      <Item key={ number.toString() } value={ number } />, 
     ); 

     return (
      <div> 
       <button onClick={() => this.setState({ test: 1 })}>Re-render list</button> 
       { listComponent } 
      </div> 
     ); 
    } 
} 

的這裏是項目:

class Item extends React.Component { 
    render() { 
     return (
      <div>{ this.props.value + ', rendered time:' + new Date().getTime() }</div> 
     ); 
    } 
} 

當我點擊按鈕,狀態已更新,因此List組件重新呈現。

但是,如果我的理解是正確的,這些項目不應該重新呈現,因爲關鍵項目沒有改變。但是它會在時間戳更新後重新渲染。

有人可以解釋我爲什麼嗎?

回答

3

你的理解是完全錯誤的

key的全部目的,是爲ordering而非rendering。 圖像你有項目a,b,c,d和重新排序然後通過開關a和c,即c,b,a,d。 如果沒有這個鍵,就很難反應如何將舊的虛擬DOM轉換爲新的虛擬DOM。

請仔細閱讀本 https://facebook.github.io/react/docs/lists-and-keys.html

1

通過重新渲染組件,您還可以在所有子組件上重新渲染鏈式反應。

如果您希望阻止子組件重新渲染(如果某些傳遞的道具沒有發生變化),則可以使用生命週期方法shouldComponentUpdate()

class Item extends React.Component { 
    shouldComponentUpdate(nextProps) { 
     // only re-render if props.value has changed 
     return this.props.value !== nextProps.value; 
    } 

    render() { 
     return (
      <div>{ this.props.value + ', rendered time:' + new Date().getTime() }</div> 
     ); 
    } 
} 
+0

我明白,但後來什麼是一種針對陣列的項目的一個關鍵性質的觀點? – lost17

+0

我如何理解它,這些鍵只是性能優化,用於比較列表項目中是否有任何更改。與重新渲染或不重新渲染無關。以下是關於爲什麼鍵有必要的深入解釋:https://facebook.github.io/react/docs/reconciliation.html#recursing-on-children –

0

每當您的狀態發生變化時,整個組件將被React重新渲染。如果您尚未將shouldComponentUpdate()函數設置爲返回false,則默認爲true。看看React's component lifecycle

相關問題