我正在尝试采用表单值并将其传递给API调用,但是变量
${city}
被视为字符串。我查看了fetch调用中变量用法的其他示例,这似乎是正确的。我在做什么错了?
功能:
class App extends Component {
getWeather = async (e) => {
const api_key = '11deac5d16f942afda257188d880da59';
e.preventDefault();
const city = e.target.elements.city.value;
const country = e.target.elements.country.value;
const call = await fetch('http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=11deac5d16f942afda257188d880da59');
const data = await call.json();
console.log(data);
}
表格:
import React from "react";
class Form extends React.Component {
render() {
return (
<form onSubmit={this.props.getWeather}>
<input type="text" name="city" placeholder="City" />
<input type="text" name="country" placeholder="Country" />
<button>Fetch Weather</button> </form>
);
}
};
export default Form;
答案 0 :(得分:1)
您需要使用反引号
`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=11deac5d16f942afda257188d880da59`
对比您拥有的东西
'http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=11deac5d16f942afda257188d880da59'
答案 1 :(得分:1)
ES6中的字符串插值应与反引号一起使用。
根据您的情况,更改此行:
const call = await fetch('http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=11deac5d16f942afda257188d880da59');
到
const call = await fetch(`http://api.openweathermap.org/data/2.5/weather?q=${city},${country}&appid=11deac5d16f942afda257188d880da59`);