簡體   English   中英

當道具更改時,React 組件不會重新渲染

[英]React component not rerendering when props changes

這是我的 2 個 React 組件——父和子

class ParentComponent extends Component{

 render(){      
    /* consultations comes from redux store 
    and looks like { consultation_id:123, date:10/12/2013 } */
   return(
    _.map(this.props.consultations,(consultation)=>{

      return{
        <ChildComponent consultation={consultation} />
      }
    })
   );
  }
}

class ChildComponent extends Component{

  render(){
  return(
    <div>this.props.consultation.date</div> 
  );
  }
}

我的問題是我有某些修改咨詢對象的操作。 例如:父組件中的props.consultation.date發生了變化,但是子組件不會重新渲染以顯示最新的咨詢日期。

但是,我注意到,如果我將咨詢對象中的每個項目發送到像<ChildComponent date={this.props.consultation.date} />這樣的子組件,它會在日期更改時<ChildComponent date={this.props.consultation.date} />

知道為什么當作為對象發送的道具發生變化時,React 不會重新渲染組件嗎?

我總是可以解決這個問題,但想知道這是一個錯誤還是我遺漏了什么?

您應該明確地將帶有consultation_id的key prop 添加到子元素中。 React 在沒有 key prop 的情況下重新渲染元素可能會出現問題!

解決辦法是將consultation={consultation}改為consultation={...consultation}. 我仍然不確定為什么,但它有效!

當您映射一組項目時,您需要向每個項目傳遞一個唯一的key屬性。 這表示對哪個元素是哪個做出反應。

...

_.map(this.props.consultations, consultation => {
  return (
    <ChildComponent 
      key={consultation.id} 
      consultation={consultation} 
    />
  )
})

您指定的詳細信息表示您更改了父組件中相同對象的日期~咨詢,並且您的父組件正在獲取數據作為道具。 現在,如果您改變相同的咨詢對象,它不會使組件重新渲染。

consultation.date = /* some other date */;

它不會重新渲染組件。

但是,如果您更改對象的引用,例如:

newConsulationData = { ...consultation }
newConsultationData.date = /* some other date */;

它會工作得很好。

在您的場景中,當您直接改變 props 數組對象並傳遞相同的數組時,您可能會遇到問題,因此我建議您更改咨詢數組的引用:您需要

 newConsulations = [ ...consultations ];
 newConsultations[index of consultation].date = /* some other date */;

這應該可以解決您的問題。 在使用 react 時,如果您想在更改上重新渲染組件,請盡量不要改變對象。

我認為這可能與數據類型有關。

第一種方法是將Object傳遞給子組件,

<ChildComponent consultation={consultation} />

第二種方法是將String傳遞給子組件。

<ChildComponent date={this.props.consultation.date} />

當對象consultation的屬性date改變時,對象的索引不會改變。 我認為 react 是通過索引引用一個對象。 對象返回一個索引而不是確切的值。 索引是對象在內存中存儲的具體地址。 但是字符串或布爾值或數字直接返回值。

我認為 react 是按索引比較對象,並按值比較字符串。 在第一種方法中,索引不會更新,因此不會發生重新渲染。


第三種方法使用擴展符號提取對象屬性。

<ChildComponent consultation={...consultation} />

我認為 react 在這種方法中引用了屬性本身,因為每個屬性都被提取出來。 它不再引用對象,因此重新渲染工作。


(我這里用了一些I think說法,因為這只是我的猜測。還需要官方文件來支持。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM