老师,您在讲SCU时,说这种写法会导致SCU函数,旧值和新值一样,会导致bug
父组件在state里定义了fruits数组,然后往数组添加数据:
this.state.fruits.push( { id: +new Date(), name: '西瓜'+Math.random() * 100 })
this.setState({
fruits: this.state.fruits
})
子组件:
shouldComponentUpdate(nextProps, nextState) {
console.log(nextProps.fruits, this.props.fruits)
if (_.isEqual(nextProps.fruits, this.props.fruits)) {
return false
}
return true
}
我把nextProps.fruits, this.props.fruits都打印出来,确实是一样的,scu返回false。
但是,我尝试这样写了一下:
父组件定义了一个数字类型的count然后加1:
this.state.count = this.state.count + 1;
this.setState({
count: this.state.count
})
子组件:
shouldComponentUpdate(nextProps, nextState) {
console.log(nextProps.count, this.props.count)
if (this.props.count === nextProps.count) {
return false
}
return true
}
输出的 nextProps.count, this.props.count 是不一样的,新值比旧值多了1,scu就返回true了。
上下两处代码出现差异的原因是因为 fruits是对象类型的,nextProps.fruits 和 this.props.fruits 都指向了同一个地址吗?