2017-03-02 63 views
1

我熟悉Javascript函數綁定。但我不明白爲什麼在以下React.js片段是再次與這個。具有與構造共同的東西,因爲這構造可根據使用情況有不同的價值觀?在構造函數中綁定(this)在ReactJS中做什麼

預先感謝您的答覆

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> 
    ) 
    } 
} 

回答

2

什麼this.search.bind(this)做它,它是內部的功能鍵this結合的情況下你的陣營組件以及它的基本含義是,只要你嘗試訪問React Component的屬性,您可以訪問它就像this.props,因爲this將引用React組件的上下文,而不是函數本身。

this.searchbind前的意義在於,它試圖訪問功能search這是在React Componentcontext,因此你只有一次,而不是兩次結合它。

我希望我能夠說明情況正常

2

你爲什麼說 「又」?你只綁定一次,而不是兩次。

從_underscores庫去抖需要一個函數並返回另一個函數,因此要在搜索函數中獲取this上下文,您需要將其綁定到search

它通常是完全一樣的具有約束力的功能在構造函數中。

3

你不應該使用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> 
    ) 
    } 
} 
1

這裏的差異是如何工作的一個例子 -

正如你可以看到,第一個電話會記錄「未定義」,第二個將記錄「酒吧」,因爲第一個呼叫沒有被綁定,並調用函數間接(如承諾的結果或回調)不守參考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()

相關問題