2017-06-18 207 views
0
constructor(props) { 
    super(props); 
    this.submitQA = this.submitQA.bind(this); 
    this.onSearchChange = this.onSearchChange.bind(this); 
    this.isSearched = this.isSearched.bind(this); 
    this.answerSubmitted = this.answerSubmitted.bind(this); 
    this.reset = this.reset.bind(this); 
    this.state = { 
    answers: [], 
    answer: '', 
    searchTerm: '', 
    } 
} 

reset() { 
    console.log("reset"); 
} 

render() { 
    const answer = true; 
    return (
    <div className="App"> 
     <div className="center"> 

     <form > 
     Search: <input type="text" onChange={this.onSearchChange} /><br/> 
     </form> 

     <form onSubmit={this.submitQA}> 
      Q & A: 
      <input type="text" placeholder=" Course/Q/A"/> 
      <button type="submit"> Submit </button> 
     </form> 
     <span>{basicFormat}</span> 
     </div> 

     { 
     this.state.answers.filter(this.isSearched(this.state.searchTerm)).map((item) => { 
      return (
      if(answer) { 
       this.reset; 
      } 
      <div> 
       <form onSubmit={this.answerSubmitted}> 
       <text> {item} </text> 
       <input type="text" placeholder="answer the question"/> 
       </form> 
      </div> 
     ) 
     }) 
     } 
    </div> 
); 
} 

爲什麼我不能在這個渲染方法中使用任何邏輯?保持給我意想不到的令牌。沒有看到任何問題。看了一些教程,他們正在做同樣的事情,但爲什麼我會拋出一個錯誤?渲染方法不能有條件地渲染js

回答

1

您已經在JSX中包含了一個Javascript if聲明,並與JSX混合使用。 Quoting the React documentation

if語句和for循環不是JavaScript表達式,所以他們不能在JSX直接使用。相反,你可以把它們放在周圍的代碼中。

要解決的意外的標記錯誤,return之前移動if聲明:

{ 
    this.state.answers.filter(this.isSearched(this.state.searchTerm)).map((item) => { 
    if(answer) { 
     this.reset(); 
    } 
    return (
     <div> 
     <form onSubmit={this.answerSubmitted}> 
      <text> {item} </text> 
      <input type="text" placeholder="answer the question"/> 
     </form> 
     </div> 
    ) 
    }) 
} 

我也建議您在render函數的返回之前執行的映射。這樣,渲染更加清晰地與數據操作分開。

render() { 
    const answer = true; 
    const answerForms = this.state.answers 
    .filter(this.isSearched(this.state.searchTerm)) 
    .map((item) => { 
     if (answer) { 
     this.reset() 
     } 
     return (
     <div> 
      <form onSubmit={this.answerSubmitted}> 
      <text> {item} </text> 
      <input type="text" placeholder="answer the question" /> 
      </form> 
     </div> 
    ) 
    }) 

    return (
    <div className="App"> 
     <div className="center"> 
     <form > 
      Search: <input type="text" onChange={this.onSearchChange} /><br /> 
     </form> 
     <form onSubmit={this.submitQA}> 
      Q & A: 
      <input type="text" placeholder=" Course/Q/A" /> 
      <button type="submit"> Submit </button> 
     </form> 
     <span>{basicFormat}</span> 
     </div> 
     {answerForms} 
    </div> 
) 
}