javascript - React 不会将 props 传递给 API 链接

标签 javascript reactjs

http://codepen.io/beckbeach/pen/mWqrep我的代码笔

React 不会将 props 传递给我的 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/en-US/docs/Web/JavaScript/Reference/Template_literals

Template literals are enclosed by the back-tick () (grave accent) character instead of double or single quotes. Template literals can contain place holders. These are indicated by the Dollar sign and curly braces (${expression}). The expressions in the place holders and the text between them get passed to a function. The default function just concatenates the parts into a single string. If there is an expression preceding the template literal (tag here), the template string is called "tagged template literal". In that case, the tag expression (usually a function) gets called with the processed template literal, which you can then manipulate before outputting. To escape a back-tick in a template literal, put a backslash \ before the back-tick.

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

关于javascript - React 不会将 props 传递给 API 链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42864545/

相关文章:

javascript - imacros 函数 iimPlay() 丢失先前建立的代理连接

Javascript:这个 javascript 功能是什么

javascript - Sublime Text 3 在按 Enter 键后仅在 javascript 中的括号中缩进一个额外的制表符

javascript - 如何从 javascript 中的 API 调用返回值到 React 组件

javascript - 使用从 Alphavantage 返回的 axios 对象更新 ReactJS 状态

javascript - 获取JS中特定路径(不包括根目录)的cookie

javascript - angular-ui:ui-router 动态路由和状态

javascript - 使用 javascript 对象重复 html 代码的最佳方法是什么?

javascript - 当 parent 停止传播时如何让 A 标签点击?

javascript - 在 Formik Form 上更新 initialValues Prop 不会更新输入值