[英]how to access functions outside of web3 scope?
我正在构建一个react-web3应用程序。
如何在web3方法中访问超出this.setState之类范围的方法?
componentDidMount() {
var events = contractInstance.allEvents({fromBlock: 0, toBlock: 'latest'});
events.watch(function(error, result){
this.setState({result: result})
});
}
}
TypeError:无法读取未定义的属性“ setState”
我可以使用过滤器方法(web3.eth.filter())轻松地做到这一点,但不能使用事件
您可以使用箭头函数作为回调:
events.watch((error, result)=>{
this.setState({result: result})
});
对于所有箭头功能,“ this”在封闭的上下文中将具有相同的“ this”值。 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/this
请注意,例如,如果直接在componentDidMount()或在componentWillMount()的上下文中执行setState,它将如何完美工作。 在那些地方,“ this”指的是您所期望的组件对象。 但是,一旦定义了回调函数,该函数内部的“ this”值可能会根据回调的使用方式而改变。 因此,要强制您回调中的'this'值为您想要的值,可以使用上述的arrow函数。 因为对于所有箭头功能,“ this”在封闭的上下文中将具有相同的“ this”值。
或者,您可以使用bind:
events.watch(function(error, result){
this.setState({result: result})
}.bind(this));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.