getDerivedStateFromProps中的状态更新是否与渲染同步?

时间:2019-06-22 22:38:22

标签: reactjs react-state-management react-state getderivedstatefromprops

由于getDervivedStateFromProps在每次 渲染之前被调用,因此我认为状态保证可以在渲染之前同步更新(即不会与批处理同步)像正常的setState通话一样可能会进行其他setState个通话吗?)

换句话说,是否保证在getDerivedStateFromProps中发生的任何更新都会反映在以下render中?

1 个答案:

答案 0 :(得分:0)

来自React的官方文档: https://reactjs.org/docs/react-component.html#static-getderivedstatefromprops

  在初始安装和后续更新上,都在调用render方法之前立即调用

getDerivedStateFromProps 。它应该返回一个对象以更新状态,或者返回null则不更新任何内容。

还:

  

请注意,无论原因如何,都会在每个渲染器上触发此方法。

所以我会说答案是肯定的,但我会避免使用它。请检查以下内容:https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html