Problems caused by functions with () and without () in react

1. react-ant-design-mobileBUG caused by a function definition when the component is used once .

  • code show as below
这里要实现的功能是,定义一个Toast回调函数,在提示之后进行一系列操作。
  • Wrong way
    }).then(() => {
    
    
      Toast.success('发布成功', 1, this.onClose());
    });
  }

  onClose = () => {
    
    
  ........
  }
  • The correct way of writing is to remove the parentheses of this.onClose. In fact, it is also a problem caused by inadvertently written parentheses. If there are parentheses, the content of the onClose function does not achieve the purpose of callback, but executes immediately.
    }).then(() => {
    
    
      Toast.success('发布成功', 1, this.onClose);
    });
  }

  onClose = () => {
    
    
  ........
  }

2. Check it out specifically

函数只要是要调用它进行执行的,都必须加括号。此时,函数()实际上等于函数的返回值。当然,有些没有返回值,但已经执行了函数体内的行为,这个是根本,就是说,只要加括号的,就代表将会执行函数体代码。


不加括号的,都是把函数名称作为函数的指针,用于传参,此时不是得到函数的结果,因为不会运行函数体代码。它只是传递了函数体所在的地址位置,在需要的时候好找到函数体去执行。

3. This reminds me of a React problem I encountered before, and it is the same reason
4. Hereby write down
Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45416217/article/details/109457869