如何访问web3范围之外的函数?

时间:2018-01-21 16:35:43

标签: reactjs web3js web3

我正在构建一个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'

我可以使用filter方法(web3.eth.filter())轻松完成,但不能使用事件

1 个答案:

答案 0 :(得分:0)

您可以使用箭头功能作为回调:

   events.watch((error, result)=>{
        this.setState({result: result})
    });

对于所有箭头函数,'this'将在封闭上下文中采用相同的'this'值。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

请注意如果直接在componentDidMount()中或者在componentWillMount()的上下文中执行setState,它可以完美地工作。在这些地方,'this'指的是您的组件对象,正如您所期望的那样。但是一旦定义了回调函数,该函数中“this”的值可能会根据回调的使用方式而改变。因此,要在回调中强制“this”的值为您想要的值,您可以使用上述箭头函数。因为对于所有箭头函数,'this'将在封闭上下文中采用相同的'this'值。

或者,您可以使用bind:

   events.watch(function(error, result){
       this.setState({result: result})
   }.bind(this));
相关问题