2017-08-08 26 views
1

在接收新道具的組件中,發生了一個奇怪的行爲。該組件將收到一個對象和一個日期對象。React更新生命週期方法返回日期相同的道具

每當對象更新時,componentWillUpdate(nextProps, nextState) nextProps.someObject將按照預期返回與this.props.someObject不同的對象。 但是,當更新日期對象時,this.props.someObject已包含存儲在nextProps中的新更新日期。

我在這裏丟失了關於數據類型或引用的內容?

EDIT

用一個例子:

  1. 渲染SomeComponent與日期= 2017年8月8日,並以{名稱: 「約翰」}對象
  2. 更新SomeComponent與日期= 09/08/2017,並以{名: 「Doe的」}對象

    SomeComponent date={newDate} someObject={newSomeObject} 

    componentWillUpdate: function(nextProps, nextState){ 
     console.log(nextProps.date !== this.props.date); // at update: false 
     console.log(nextProps.someObject.name !== this.props.someObject.name); // at update: true 
    } 
+1

添加一個例子。 –

+0

你是否在同一時間更新兩個道具?或者可能沒有同步,所以你會得到2個componentWillUpdate調用,也許你會混淆2 –

+0

否道具更新是基於兩個不同時發生的動作。因此,無論JavaScript對象如何,this.props.date始終等於nextProps.date(是更新後的值) – BrFreek

回答

1

對待state好像它是不可變的。

嘗試在瀏覽器的代碼:

var d = new Date(); 
 
var d2 = d; 
 

 
d2.setDate(7); 
 

 
d == d2;

d2d指向同一個對象。

現在asssuming您得到您的狀態:

let newDate = this.state.date

不管你什麼更新newDatethis.state.date也發生了變化。你可以在你的代碼中嘗試自己。

將相同的情況應用於其他數據類型(如數組)。

我建議使用date-fnsthe creator of Redux stated

相關問題