2017-08-01 38 views
2

我正在研究React項目,我嘗試編譯但找不到爲什麼會出現此語法錯誤。具體來說,在這種情況下,模式「{()=> {}()}」在做什麼?JSX內部立即調用的函數表達式

Module build failed: SyntaxError: Unexpected token, expected } (35:9) 

33 |    return (<div className="loading" />); 
34 |   } 
35 |   }()} 
    |  ^
36 |  </div> 
37 | ); 
38 | } 

@ ./src/containers/SearchApp.js 7:0-52 
@ ./src/containers/App.js 
@ ./src/index.js 
@ multi ./src/index 

的代碼的一部分:

render() { 
return (
    <div> 
    <div className="form-group"> 
     <input onKeyDown={this.searchEnter.bind(this)} type="text" ref="tag" className="form-control input-lg search-bar" placeholder="Enter the tag..." /> 
     <button onClick={this.searchClick.bind(this)} type="button" className="btn btn-default search-button">Search!</button> 
    </div> 
    {()=>{ 
     if (this.props.status === 'PENDING') { 
     return (<div className="loading" />); 
     } 
    }()} 
    </div> 
); 
+0

看起來像有人拿了一個老同學IIFE,'函數(){...}()',並試圖使其成爲性感()=> {...})()' –

+1

Jaromanda是正確的inline IIFE的模式是()=> {...}()不知道箭頭IIFE的必須是'(()=> {})()'。請記住,在IIFE的函數中,第一組括號中的內容將被評估。然後第二組圓括號將調用該函數。 – Rodrigo

+0

謝謝你的評論...!在它周圍添加一個包裝解決了語法錯誤..!我剛開始學習JavaScript,需要學習這麼多。我總是感謝你的幫助。 – tak

回答

2

這是Immediately-invoked function expression

錯誤代碼?

您需要包裝內()函數,檢查:

{ 
    (() => { 
     if (this.props.status === 'PENDING') { 
     return (<div className="loading" />); 
     } 
    })() 
} 

什麼模式, 「{()=> {}()}」,在這種情況下做?

直接我們不能在JSX中放入if/else語句或任何其他語句,所以爲此我們需要創建一個函數並將所有邏輯放在裏面。

DOC

if-else語句不JSX裏面工作。這是因爲對於函數調用和對象構造,JSX只是 語法糖。如果三元表達式不夠健壯,則可以使用JSX之外的if語句來確定應該使用哪些組件。或者,如果您更喜歡「內聯」美學,請在JSX中定義立即調用的函數表達式

編寫相同的代碼的另一種方法:

render(){ 
    return(
     <div> 
      <div className="form-group"> 
       .... 
      </div> 
      {this._callFun()}  
     </div> 
    ) 
} 

_callFun(){ 
    if (this.props.status === 'PENDING') { 
     return (<div className="loading" />); 
    } 
} 
+0

這正是模式和修改您列出的代碼解決了錯誤..!非常感謝。 – tak

+0

很高興,它解決了你的問題:) –

相關問題