react.js 构造函数调用了两次 [英] react.js constructor called twice

查看:24
本文介绍了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://stackoverflow.com/a/61443443/6014725

React constructor is called twice in strict mode. https://stackoverflow.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 了解更多信息

这篇关于react.js 构造函数调用了两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆