【发布时间】:2016-05-24 21:40:48
【问题描述】:
如果我理解正确,组件的 React 生命周期应该确保在 componentWillReceiveProps 之前调用 componentDidMount。当我在组件的初始安装上测试它时,它似乎以这种方式工作。但是当组件之前已经安装并重新安装时,顺序是相反的。这是预期的行为吗?以下代码说明了可以通过这种方式引入的潜在错误:
class Example extends React.Component {
componentDidMount() {
this.something = { foo: 'bar' };
}
componentWillReceiveProps(nextProps) {
this.something.foo;
// Throws a TypeError if this code is reached before
// componentDidMount is called.
}
}
【问题讨论】:
-
你能在小提琴上分享你的测试台吗?
componentWillReceiveProps在挂载期间不会被调用,因为无论如何道具都会进来。稍后,它在收到新道具时被调用。但是componentDidMount根本不会被调用,除非该组件已经被首先卸载。
标签: reactjs