react.js constructor called twice

后端 未结 3 1925
北恋
北恋 2020-12-18 10:51

I a have post list and I am trying to call an action inside of constructor or componentDidMount for each post. But somehow when I send a new message constructor and componen

相关标签:
3条回答
  • 2020-12-18 11:03

    When the code in the constructor is run twice, you can be sure that the component is being created anew two times. This can happen of various reasons, the simplest reason is probably that the component is being used on multiple places:

    <MyComponent />
    <MyComponent />
    

    Another reason could be that you have conditional rendering, meaning perhaps you're rendering based on a boolean, that changes:

    { myBoolean && <MyComponent /> }
    

    If you toggle myBoolean two times, the constructor will be executed two times.

    0 讨论(0)
  • 2020-12-18 11:09

    Well, when your constructor and your componentDidMount function both fire twice you can be sure that the component in question is constructed twice somewhere.

    0 讨论(0)
  • 2020-12-18 11:17

    React constructor is called twice in strict mode. https://stackoverflow.com/a/61443443/6014725

    This is not a bug, but on purpose behavior to ensure that the constructor is pure. https://github.com/facebook/react/issues/12856#issuecomment-613145789

    Learn more with https://reactjs.org/docs/strict-mode.html

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