Why use getDerivedStateFromProps instead of componentDidUpdate?

后端 未结 2 721
孤城傲影
孤城傲影 2021-01-30 06:59

As read in this React Github issue I see more and more that

the cost of render() is relatively small

In React 1

2条回答
  •  情歌与酒
    2021-01-30 07:41

    So Dan Abramov answered on Twitter and it seems like there are 2 reasons why you should use getDerivedStateFromProps instead of componentDidUpdate + setState:

    setState in componentDidUpdate causes an extra render (not directly perceptible to user but it slows down your app). And you render method can’t assume the state is ready (because it won’t be the first time).

    • Performances reason: it avoids unnecessary re-render.
    • As getDerivedStateFromProps is called before rendering on init, you can initialise your state in this function instead of having a constructor to do so. Currently you had to have a constructor or componentWillMount to init your state before initial rendering.

提交回复
热议问题