Why getDerivedStateFromProps is called after setState?

后端 未结 5 1594
别那么骄傲
别那么骄傲 2021-02-06 23:02

React introduced new static method getDerivedStateFromProps(props, state) which is called before every render method, but why? Calling it after prop change makes se

5条回答
  •  一向
    一向 (楼主)
    2021-02-07 00:06

    you have the answer in your question itself. "which is called before every render method". Whenever you do a setState the render method will be called.

    I would suggest that you lift the state variables currentMonth and currentYear to the parent component and pass them as prop along with other three. You can also pass the change handler as prop and call it from the child.

    on initial render - currentMonth and currentYear can be set to null, so that you can have the logic for showing default stuff. When someone chicks on month name, you can call the changeHandler from parent which will pass the new prop. Now in getderivedstatefromprops you no longer have currentMonth and currentYear as `null so you know that the month has changed.

提交回复
热议问题