React官网文章(A=>B)!=>(B=>A)译文 --By Jim Sproch

https://reactjs.org/blog/2016/01/08/A-implies-B-does-not-imply-B-implies-A.html

componentWillReceiveProp 方法的描述是:当props改变时componentWillReceiveProps 将会作为页面重新渲染的结果被调用。许多人认为如果componentWillReceiveProps 方法被调用,那么props一定已经改变了。这种理解是不正确的。总结起来就是一句话:A推出B并不意味着B能推出A

例如:如果我吃了发霉的食物,那么我就会生病”并不意味着“如果我生病了,那么我一定吃了发霉的食物”。我生病还有很多其他原因。例如,可能流感在办公室里传播。类似地,即使props没有更改,也有很多原因导致componentWillReceiveProps 被调用。

如果你不相信,看下面代码:

class Component extends React.Component {
  componentWillReceiveProps(nextProps) {
    console.log('componentWillReceiveProps', nextProps.data.bar);
  }
  render() {
    return <div>Bar {this.props.data.bar}!</div>;
  }
}
​
var container = document.getElementById('container');
​
var mydata = {bar: 'drinks'};
ReactDOM.render(<Component data={mydata} />, container);
ReactDOM.render(<Component data={mydata} />, container);
ReactDOM.render(<Component data={mydata} />, container);
 

这里调用了3次ReactDOM.render(), props是一样的。componentWillReceiveProps 调用了2次。因为有两次更新,每次更新调用一次componentWillReceiveProps 方法。虽然props并没有变化。

为了理解为什么,我们需要思考发生了什么。看下面例子,数据在第一次render和两次更新之间可能已经改变了,但是React自身无法知道这种变化。所以必须调用componentWillReceiveProps 方法,因为组件需要被新的props通知,才能知道这种变化。(自己的理解)所以即使属性一样,也需要componentWillReceiveProps 方法来告知,否则自己无法感知。

var mydata = {bar: 'drinks'};
ReactDOM.render(<Component data={mydata} />, container);
mydata.bar = 'food'
ReactDOM.render(<Component data={mydata} />, container);
mydata.bar = 'noise'
ReactDOM.render(<Component data={mydata} />, container);

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值