Redux React:无法在另一个 class 的函数内访问 'this'

Redux React: Not able to access 'this' inside a function of another class

我有一个名为 iccSdk 的 class,它有一个名为 on 的函数。现在在我的 React 的 render 中,我正在调用函数 iccSdk.on()。此外,我想从此函数中分派一个动作,所以我尝试使用 this.props.actions.chatConnect(data);this 在这里变得未定义。

第一次尝试:

render() {
    console.log(this);
    iccSdk.on('connect', function(data) {
      console.log(this);
      this.props.actions.chatConnect(data);
    });
...
}

在上述情况下,this 在函数内部显示为未定义,但在我的 iccSdk.on() 函数外部看起来不错。

第二次尝试:

render() {
    var t = this;
    iccSdk.on('connect', function(data) {
      t.props.actions.chatConnect(data);
    });
...
}

在第二次尝试中它工作正常但我怀疑这样做是不是一个好习惯,我也很困惑为什么 this 在我的 iccSdk.on()

This 是对提供给方法的对象的引用。在一个方法中,您可以访问给定的对象,它是 This。但是 on 方法属于 iccSdk 所以,它不能通过这个变量访问其他对象。每个方法只能访问它自己的对象。

所以,如果你想在一个方法中访问另一个对象,你可以使用你的第二次尝试(我想这很正常),或者你可以像这样将方法绑定到你想要访问的对象:

function () {
    console.log(this)
}.bind(this)

函数创建了一个新的作用域。因此上下文 (=this) 不同或不存在。你的第二种方法很好。

其他方法:

箭头函数:

箭头函数不会为该函数创建新的上下文。因此,您可以在函数中使用相同的 this。为此需要 ES6。

render() {
    console.log(this);
    iccSdk.on('connect', data => {
      console.log(this);
      this.props.actions.chatConnect(data);
    });
...
}

绑定

使用绑定函数,您可以将 "this" 绑定到您的函数。

render() {
    console.log(this);
    iccSdk.on('connect', function(data) {
      console.log(this);
      this.props.actions.chatConnect(data);
    }.bind(this));
...
}

thisArg

iccSdk.on 也可能需要 "this argument"。我不确定是否如此。您可以在此处阅读有关 thisArg 的更多信息:https://h3manth.com/new/blog/2014/thisarg-in-javascript/