无法从事件触发功能

问题描述

我不是一个熟练的 React 程序员,但仍然希望有人愿意解释我所缺少的:

我想要的 我想在 Metamask 中更改帐户,检测“accountsChanged”事件,并触发 testFunction。

什么有效 我可以通过单击测试功能按钮来触发 testFunction。 我可以检测到帐户更改(出于某种原因,每次更改时都会检测到大约 5 次)。

什么不起作用 我无法在帐户更改时触发 testFunction 并收到消息 TypeError: this.testFunction is not a function

怀疑我在这里遗漏了一些关于 React 的基本原理...感谢所有回复

class App extends Component {
   ...
   componentDidMount = async () => {
      ...
   };

   testFunction = async =>{
      console.log("triggered the test function");
   };

   render() {
    window.ethereum.on('accountsChanged',function (accounts) {
      console.log("account change detected");
      this.testFunction(); --> this is not working
    });

     return (
         <div className="App">
           <button type="button" onClick={this.testFunction}>test function</button>
         </div>
       );
     }
  }

解决方法

您需要将普通函数转换为箭头函数。因为普通函数从调用它的对象派生 this,但箭头函数从周围范围派生 this,因此在箭头函数中 this 将指向您的类并且可以访问方法。

window.ethereum.on('accountsChanged',accounts => {

此外,您可以继续使用普通函数,但在这种情况下,您可以将 this 存储在其他一些变量中,例如 that' or 'self 并在普通函数中使用它来调用类的方法。

let that = this;
window.ethereum.on('accountsChanged',function(accounts){
 that.testFunction() //this will work

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...