Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

javascript - 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 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();
         }
      }   
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...