react.js构造函数被调用两次

react.js构造函数被调用两次

问题描述:

我有一个帖子列表,我试图为每个帖子在构造函数或componentDidMount内部调用一个动作.但是以某种方式,当我发送新消息时,构造函数和componentDidMount函数会被调用两次.

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.

我如何避免这些情况.我试图像这样使用componendDidUpdate函数:

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();
         }
      }   
}

在严格模式下,两次调用了React构造函数. https://*.com/a/61443443/6014725

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

这不是错误,而是有目的的行为,以确保构造函数是纯净的. https://github.com/facebook/react/issues/12856#issuecomment-613145789

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

通过 https://reactjs.org/docs/strict-mode.html 了解详情

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