Javascript React不会将道具传递给API链接
我的密码笔 React不会在我的API链接中将props传递给${this.state.query}。我做错了什么Javascript React不会将道具传递给API链接,javascript,reactjs,Javascript,Reactjs,我的密码笔 React不会在我的API链接中将props传递给${this.state.query}。我做错了什么 class App extends React.Component { constructor(props) { super(props) this.state = { query: '' } } searchFunction() { fetch('http://api.openweatherma
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'))
类应用程序扩展了React.Component{
建造师(道具){
超级(道具)
此.state={
查询:“”
}
}
searchFunction(){
取('http://api.openweathermap.org/data/2.5/weather?zip=${this.state.query},us&appid=748F6431ACEE33C207BEE1A969F6E3'{
方法:“获取”
})。然后((res)=>{
res.json().then((数据)=>{
控制台日志(数据);
})
})
.catch((错误)=>{
控制台日志(err);
})
}
render(){
返回(
看看天气!
{this.setState({query:event.target.value}}}/>
this.searchFunction()}>检查天气
)}
}
ReactDOM.render(,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`
有关模板文本的信息:
模板文本由后面的勾号(
)包围(严重重音)
字符,而不是双引号或单引号。模板文本可以
包含占位符。这些由美元符号和符号表示
大括号(${expression})。占位符和
它们之间的文本传递给函数。默认函数
只需将各个部分连接成一个字符串。如果有
模板文本(此处为标记)前面的表达式
字符串称为“标记的模板文字”。在这种情况下,标签
表达式(通常是函数)通过已处理的
模板文本,然后可以在输出之前对其进行操作。到
在模板文本中转义一个反勾号,在
回滴答声
工作笔FWIW,这与反应本身无关。您没有正确使用模板文本。