为什么getDerivedStateFromProps每次调用两次

时间:2020-08-23 02:00:36

标签: reactjs

我的组件

<iframe src="https://codesandbox.io/embed/vigorous-sun-b7pf2?fontsize=14&hidenavigation=1&theme=dark" style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;" title="vigorous-sun-b7pf2" allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
  sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"></iframe>

getDerivedStateFromProps 应该在16.4及更高版本中的道具和状态时调用。但是为什么它叫了两次。

请帮助我理解这一点。

1 个答案:

答案 0 :(得分:0)

首先在React 16.3版本中,在更新props(http://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/)时才调用getDerivedStateFromProps()。但现在在更大的版本中,无论更新道具还是更新状态(无论重新渲染的原因),都会调用getDerivedStateFromProps()。

getDerivedStateFromProps()在render()方法之前被调用有两个原因:

  1. 初始安装
  2. 每个状态和道具更新