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);