【发布时间】:2016-12-23 17:10:10
【问题描述】:
我想避免 let that = this;,因为这似乎是一个肮脏的解决方案。是不是例如无论如何可以使用.bind(this)?
我的当前代码:
// ...
componentDidMount() {
let that = this; // <- how to avoid this line?
this.props.myService.listensTo('action', (data) => {
that.handleData(data);
});
}
handleData(data) {
// handle data
}
// ...
提前致谢!
【问题讨论】:
-
你试过
this.props.myService.listensTo('action', this.handleData.bind(this));吗? -
您不需要带有 Javascript 箭头函数的
that技巧。 -
React 在你使用箭头函数时已经绑定了 this。
-
@Jecoms - 它与 React 无关。这是 ES6 的标准特性。有关箭头函数如何处理
this的详细信息,请参阅the docs。 -
确实,只是措辞不佳。
标签: javascript reactjs react-native