react.js constructor called twice

问题: 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 compone...

问题:

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 componentDidMount functions are called twice.

 constructor(props) {
    super(props);

    if (condition1) {
       this.props.actions.action1();
    } else if (condition2) {
       this.props.actions.action2();
    }    
}

These functions are called only once when the posts are readed from a list. But when I send a new message they are called twice.

How can i avoid these situation. I tried to use componendDidUpdate function like this:

componentDidUpdate(prevProps, prevState) {     
      if (prevProps.post.id !== this.props.post.id) {
         if (condition1) {
            this.props.actions.action1();
         } else if (condition2) {
            this.props.actions.action2();
         }
      }   
}

回答1:

Well, when your constructor and your componentDidMount function both fire twice you can be sure that the component in question is constructed twice somewhere. Can you share the code where you implement the component in question with us?


回答2:

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.

  • 发表于 2019-03-13 11:55
  • 阅读 ( 799 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除