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