Setting state on componentDidMount()

后端 未结 3 1837
轮回少年
轮回少年 2020-12-04 12:17

I know that it is an anti-pattern to set state on componentDidMount and a state should be set on componentWillMount but suppose I want to set the l

3条回答
  •  时光说笑
    2020-12-04 12:38

    According to the React Documentation it's perfectly OK to call setState() from within the componentDidMount() function.

    It will cause render() to be called twice, which is less efficient than only calling it once, but other than that it's perfectly fine.

    You can find the documentation here:

    https://reactjs.org/docs/react-component.html

    Here is the excerpt from the documentation:

    You may call setState() immediately in componentDidMount(). It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues...

提交回复
热议问题