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

bur*_*nlu 8 javascript reactjs react-redux

我有一个帖子列表,我试图在每个帖子的构造函数或 componentDidMount 中调用一个动作。但不知何故,当我发送一个新的消息构造函数和 componentDidMount 函数被调用两次。

 constructor(props) {
    super(props);

    if (condition1) {
       this.props.actions.action1();
    } else if (condition2) {
       this.props.actions.action2();
    }    
}
Run Code Online (Sandbox Code Playgroud)

当从列表中读取帖子时,这些函数仅被调用一次。但是当我发送一条新消息时,它们会被调用两次。

我怎样才能避免这些情况。我尝试像这样使用 componendDidUpdate 函数:

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

pap*_*ool 17

React 构造函数在严格模式下被调用两次。 /sf/answers/4301041041/

这不是错误,而是为了确保构造函数是纯的故意行为。 https://github.com/facebook/react/issues/12856#issuecomment-613145789

通过https://reactjs.org/docs/strict-mode.html了解更多信息

  • 这是一个很好的答案。这是一个糟糕的设计选择。 (3认同)

小智 2

好吧,当你的构造函数和 componentDidMount 函数都触发两次时,你可以确定有问题的组件在某个地方被构造了两次。