请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

想问一个SCU的问题

老师,您在讲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然后加1this.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 都指向了同一个地址吗?

正在回答

1回答

前者是引用类型,后者是值类型,俩这不一样。

两个引用类型指向了同一个对象,而两个值类型就是两个不同的值

0 回复 有任何疑惑可以回复我~
  • 提问者 白夜2021 #1
    老师,既然对state里的值类型的数据,直接进行修改的话,得到的是两个不同的值,
    nextProps.count 和 this.props.count 不会相等。那是不是意味着,React的“不可变值”这个原则,只针对引用类型的数据才有效?对值类型的数据其实没有太大意义。
    this.state.count = this.state.count + 1;
    this.setState({count: this.state.count})
    nextProps.count !== this.props.count
    回复 有任何疑惑可以回复我~ 2022-01-20 09:49:42
  • 双越 回复 提问者 白夜2021 #2
    我一直都是用不可变数据,到没注意值类型。也建议你一直使用不可变数据,不要管值类型还是引用类型。
    回复 有任何疑惑可以回复我~ 2022-01-20 13:57:41
  • 提问者 白夜2021 #3
    非常感谢!
    回复 有任何疑惑可以回复我~ 2022-01-20 14:07:18
问题已解决,确定采纳
还有疑问,暂不采纳
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号