簡體   English   中英

反應應該組件更新檢測到更改

[英]React shouldComponentUpdate detect change

我必須在這里做些愚蠢的事情,但是經過一天的努力,我現在正在這里...

對於數組val每個元素,我都有一個下拉菜單,我將其保存為Component狀態:

class C extends Component {

    state = { val : [ 1,2,3,4] }
    ...

}

每個下拉菜單項中的更改都會觸發此回調:

  onChanged = (event, index) => {
    console.log("val changed");
    this.setState(state => {
      const val = state.val;
      val[index] = event.target.value;
      return { val: val };
    });
  };

現在的問題是,我無法弄清楚如何在shouldComponentUpdate檢測到此更改。 具體來說,當我更改其中一個下拉選項時,我看到val changed被記錄下來。 但是,在shouldComponentUpdate方法中, nextStatethis.state始終包含相同的值(在比較時看起來是相同的)。 因此,我無法檢測到shouldComponentUpdate的更改。 這是我正在使用的確切代碼:

shouldComponentUpdate(nextProps, nextState) {

    console.log(
      "shouldComponentUpdate",
      nextProps.val,
      this.state.val,
      nextState.val,
      this.state.val === nextState.val
    );
    return false;
}

在更改其中一個下拉選項之前,此日志記錄如下

shouldComponentUpdate, undefined, [1, 2, 3, 4], [1, 2, 3, 4], true

如果我將第一個下拉菜單從1更改為9 ,那么我會看到

shouldComponentUpdate, undefined, [9, 2, 3, 4], [9, 2, 3, 4], true

我希望在更改后我會立即看到

shouldComponentUpdate, undefined, [1, 2, 3, 4], [9, 2, 3, 4], true

請告訴我如何檢測到shouldComponentUpdate的更改或應該使用的慣用法。

編輯:

有人建議我在onChanged回調中對值數組進行slice ,即,將回調更改為:

  onChanged = (event, index) => {
    console.log("val changed");
    this.setState(state => {
      const val = state.val.slice();
      val[index] = event.target.value;
      return { val: val };
    });
  };

那沒有解決問題。 這是更改前后的控制台日志:

shouldComponentUpdate undefined (4) [1, 2, 3, 4] (4) [1, 2, 3, 4] true
val changed
shouldComponentUpdate undefined (4) [9, 2, 3, 4] (4) [9, 2, 3, 4] true 

編輯:

我傻。 有一個愚蠢的回報聲明受到打擊。 我完全想念它。 我接受以下答案,因為它們已正確說明問題。

那是因為您要使數組變異並重新使用它。

更改const val = state.val;

const val = [...state.val];

要么

const val = state.val.slice();

創建一個新的數組

JS數組按引用傳遞,而不按值傳遞。
當你做const val = state.val; val[index] = event.target.value; 它在setState之前更改狀態變量。

例:

var a = {x: [1,2,3]}
var b = a.x
b[0] = 5 // b = [5, 2, 3] and a = {x: [5,2,3]}

您可以使用切片解構來解決您的問題。

//Slice
const val = state.val.slice()
//Destructure
const val = [...state.val]

在上面的示例中:

var a = {x: [1,2,3]}
var b = [...a.x]
var c = a.x.slice()
b[0] = 5     //b = [5, 2, 3] and a = {x: [1,2,3]}
c[0] = 6    //b = [6, 2, 3] and a = {x: [1,2,3]}

暫無
暫無

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

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