【问题标题】:Not able to trigger function from event无法从事件触发功能
【发布时间】:2021-09-06 01:17:03
【问题描述】:

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

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

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

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

怀疑我在这里遗漏了一些关于反应的基本知识...感谢所有回复!

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

【问题讨论】:

  • 请尝试window.ethereum.on('accountsChanged', accounts =&gt; {
  • 感谢@RajdeepDebnath,这确实有效! 1) 知道为什么 Metamask 和其他人提出我最初使用的格式吗?见这里:docs.metamask.io/guide/accessing-accounts.html 2) 事件和函数调用一次发生 5 次 - 知道这是为什么吗?我把函数放在正确的地方了吗?
  • 请将此函数window.ethereum.on( 放在componentDidMount 中,不要放在渲染中

标签: reactjs events event-handling ethereum metamask


【解决方案1】:

您需要将普通函数转换为箭头函数。因为普通函数从调用它的对象派生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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    • 2013-10-28
    • 1970-01-01
    • 1970-01-01
    • 2020-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多