javascript - ReactJS 中的 Bind(this) 混淆

标签 javascript reactjs this bind

我正在阅读 Reactjs 和

 componentDidMount: function() {
    this.serverRequest = $.get(this.props.source, function (result) {
      var lastGist = result[0];
      this.setState({
        username: lastGist.owner.login,
        lastGistUrl: lastGist.html_url
      });
    }.bind(this));
  }

根据我的理解,将 this if 绑定(bind)到 this.setState 以便在外部调用时,this 将引用正确的对象。但为什么我们不需要它来实现 this.props.source 呢?

最佳答案

因为 this.props.source 是传递给 $.get 的参数 - 它在 componentDidMount 内执行时仍然具有正确的上下文> 方法。只有在 $.get 方法的回调中,上下文才会丢失,该上下文是从 jQuery 库中的某个位置执行的。

保留上下文的另一种方法是使用 arrow function (这是 es6,所以你现在需要一个转译器),它将为你进行绑定(bind):

$.get(this.props.source, (result) => {
  // ...
});

关于javascript - ReactJS 中的 Bind(this) 混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35947377/

相关文章:

javascript - 打开 extjs 时,折叠的面板不会创建滚动

reactjs - 每小时刷新 token 的最佳方法?

node.js - Node promise - 控制台打印嵌套但无法从 firebase 函数返回值

reactjs - 我如何使用 react 光滑 slider 来实现网格轮播布局

c++ - 将此指针推回私有(private)静态成员 vector

java - "this"指向哪里?

python - 在 C++ 中,不应该有一个类似于 'this' 指针的名称不可知的类指针供成员函数引用吗?

javascript - 检查复选框是否被选中?

javascript - object.style.height 不起作用

javascript - javascript 中的属性包