[英]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
方法中, nextState
和this.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.