簡體   English   中英

React不會將props傳遞給API鏈接

[英]React will not pass props to API link

http://codepen.io/beckbeach/pen/mWqrep我的代碼筆

React不會將道具傳遞到我的API鏈接中的$ {this.state.query}。 我究竟做錯了什么?

class App extends React.Component {                                  
constructor(props) {
super(props)
this.state = {
query: ''
  }
 }

 searchFunction() {
    fetch('http://api.openweathermap.org/data/2.5/weather?zip=${this.state.query},us&appid=748f643131acee33c207bee1a969f6e3', {
  method: 'GET'
}).then((res) => {
res.json().then((data) => {
  console.log(data);
  })
 })
    .catch((err) => {
      console.log(err);
  })
   }

 render() {
return (
  <div>
    <h1>Check The Weather!</h1>
    <div>
    <input type="text" placeholder="Enter Zipcode" value={this.state.query} onChange={event => {this.setState({query: event.target.value})}}  />
<button type="submit" onClick={() => this.searchFunction()}>CHECK WEATHER </button>
    </div>
  </div>
)}
}


ReactDOM.render(<App/>, document.getElementById('root'))

您使用單引號而不是模板文字的反引號。

'http://api.openweathermap.org/data/2.5/weather?zip=${this.state.query},us&appid=748f643131acee33c207bee1a969f6e3'

應該

`http://api.openweathermap.org/data/2.5/weather?zip=${this.state.query},us&appid=748f643131acee33c207bee1a969f6e3`

有關模板文字的信息: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Template_literals

模板文字由反引號( )(重音符號)字符,而不是雙引號或單引號。 模板文字可以包含占位符。 這些由美元符號和大括號($ {expression})表示。 占位符中的表達式及其之間的文本將傳遞給函數。 默認功能只是將各個部分串聯為一個字符串。 如果在模板文字之前有一個表達式(在此處標記),則模板字符串稱為“標記的模板文字”。 在這種情況下,將使用已處理的模板文字來調用標簽表達式(通常是一個函數),然后可以在輸出之前對其進行操作。 要在模板文字中避免反引號,請將反斜線\\放在反引號之前。

工作筆http://codepen.io/finalfreq/pen/MpONrW

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM