【问题标题】:Javascript (react native): how to avoid that = this?Javascript(反应原生):如何避免=这个?
【发布时间】: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


【解决方案1】:

基本上,箭头函数将对此有所帮助,并且由于 React-Native 不必处理浏览器兼容性问题,您可以定义如下函数:

handleData = (data) => {
  this.setState({ data });
}

如果您使用 this,您将永远不必 .bind 或 that=this。

【讨论】:

  • 另外,对于componentDidMount,你甚至不需要这样做=this,因为你使用了箭头函数。
【解决方案2】:

this 已经绑定,因为你使用了箭头函数。

// ... 
componentDidMount() {
    this.props.myService.listensTo(
        'action', 
        (data) => this.handleData(data)
    );
}

handleData(data) {
    // handle data
}
// ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-16
    • 2013-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-06
    • 2020-03-31
    • 2016-03-31
    相关资源
    最近更新 更多