【发布时间】:2018-07-01 10:50:19
【问题描述】:
我正在尝试获取表单值并将它们传递给 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;
【问题讨论】:
-
使用反引号代替单引号(此处转义)
`My name is${name}`。还要检查您的fetch call 是否正确 -
@Tico 使用 insomnia 来验证通话。改为反引号并完美运行,谢谢。
-
哈哈它发生了,很高兴我能帮忙
标签: javascript reactjs fetch