[英]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.