构造函数中的 bind(this) 在 ReactJS 中做什么

IT技术 javascript reactjs
2021-05-22 00:51:06

我熟悉 Javascript 函数bind但我不明白为什么在下面的 React.js 片段中this再次绑定到thisHas 与constructor有一些共同之处,因为根据使用情况,构造函数中的this可以具有不同的值?

预先感谢您的回复

class QuotesLibrary extends React.Component {
  constructor(props) {
    super(props);
    this.search = debounce(this.search.bind(this), 300);
  }
  search(searchTerm) {
    this.props.relay.setVariables({searchTerm});
  }
  render() {
    return (
      <div className="quotes-library">
        <SearchForm searchAction={this.search} />
        <div className="quotes-list">
          {this.props.library.quotesConnection.edges.map(edge =>
            <Quote key={edge.node.id} quote={edge.node} />
          )}
        </div>
      </div>
    )
  }
}
4个回答

你不应该使用 Function.bind(this) :你应该使用箭头函数。箭头函数绑定到类(因此绑定到组件)。

class QuotesLibrary extends React.Component {
  constructor(props) {
    super(props);
    this.search = debounce(this.search, 300);
  }

  search = (searchTerm) => {
    this.props.relay.setVariables({searchTerm});
  }

  render() {
    return (
      <div className="quotes-library">
        <SearchForm searchAction={this.search} />
        <div className="quotes-list">
          {this.props.library.quotesConnection.edges.map(edge =>
            <Quote key={edge.node.id} quote={edge.node} />
          )}
        </div>
      </div>
    )
  }
}

什么this.search.bind(this)做它,它的关键是结合this内部的功能的情况下你的阵营组件以及它的基本含义是,每当您尝试访问的属性React Component,你可以像访问它this.props,因为this随后将参照阵营组件的上下文而不是函数本身。

的意义this.search之前bind是,它试图访问功能,search这是在contextReact Component,所以你只有一次,而不是两次结合它。

我希望我能够正确解释情况

这是差异如何运作的示例 -

如您所见,第一个调用将记录“未定义”,第二个将记录“Bar”,因为第一个调用未绑定,并且间接调用函数(作为Promise结果或作为回调)不会保留引用到this当它运行-绑定告诉它什么它this指的是。

function debounce(fn, to) {
    setTimeout(fn)
}

class Foo {
  constructor () {
    this.fullName = 'Bar'
  }
  
  speak () {
    console.log("My name is", this.fullName)
  }
  
  test () {
    debounce(this.speak, 1000) // undefined
    debounce(this.speak.bind(this), 2000) // "Bar"
    
  }
}

let foo = new Foo()

foo.test()

为什么说“又”?你只能绑定一次,而不是两次。

_underscores 库中的 debounce 接受一个函数并返回另一个函数,因此要this在搜索函数中获取上下文,您需要将其绑定到search.

它与通常在构造函数中的绑定函数完全相同。