Which kinds of initialization is more appropriate in constructor vs componentWillMount?

后端 未结 2 495

If I have a React component that requires some setup (e.g. for timers, or WebAudio API, etc), I\'m having trouble deciding whether the initialization should go in cons

相关标签:
2条回答
  • 2020-12-29 04:17

    If you want to call some flux action (for ajax calls) use componentWillMount or componentDidMount.

    You can initialize state in constructor

    0 讨论(0)
  • 2020-12-29 04:21

    Normally the only thing you do in the constructor is assign your initial this.state if your component is stateful. You should not do anything else in the constructor.

    componentWillMount is generally unnecessary. I would say in most cases its use is an anti-pattern. One reason people use it is for updating the state from an external source one last time before rendering but technically assigning it in the constructor is equivalent. The only minor convenience it affords is that you can setState inside it but you can’t inside the constructor.

    For any side effects (data fetching or DOM manipulation) you should use componentDidMount.

    0 讨论(0)
提交回复
热议问题