【发布时间】: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 => { -
感谢@RajdeepDebnath,这确实有效! 1) 知道为什么 Metamask 和其他人提出我最初使用的格式吗?见这里:docs.metamask.io/guide/accessing-accounts.html 2) 事件和函数调用一次发生 5 次 - 知道这是为什么吗?我把函数放在正确的地方了吗?
-
请将此函数
window.ethereum.on(放在componentDidMount中,不要放在渲染中
标签: reactjs events event-handling ethereum metamask