【发布时间】:2019-08-06 22:58:47
【问题描述】:
我正在尝试遵循 youtube 上的教程,该教程使用 openweathermap api 根据用户的两个输入来显示某个位置的天气,但我收到此错误:
Unhandled Rejection (TypeError): Cannot read property 'city' of undefined
_callee$
src/App.js:16
13 |
14 | getWeather = async e => {
15 | e.preventDefault();
> 16 | const city = e.target.element.city.value;
| ^ 17 | const country = e.target.element.country.value;
18 | const api_call = await fetch(
19 | `api.openweathermap.org/data/2.5/weather?q=${city},${country}&APPID=${API_KEY}`
这里有很多关于类似问题的帖子,人们建议在 App.js 中添加构造函数并绑定提交和 getWeather 函数。我一直在尝试,它给了我一个不同的错误:
TypeError: Cannot read property 'getWeather' of undefined
new App
src/App.js:10
7 |
8 | class App extends React.Component {
9 | constructor() {
> 10 | this.getWeather = this.getWeather.bind(this);
11 | this.onSubmit = this.onSubmit.bind(this);
12 | }
13 |
我的代码目前看起来像这样-App.js:
import React from "react";
import Titles from "./components/Titles.js";
import Form from "./components/Form.js";
import Weather from "./components/Weather.js";
const API_KEY = "ca4d2addb51bf577deda4bf791f7f683";
class App extends React.Component {
constructor() {
this.getWeather = this.getWeather.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
getWeather = async e => {
e.preventDefault();
const city = e.target.element.city.value;
const country = e.target.element.country.value;
const api_call = //makes api call
const data = await api_call.json();
console.log(data);
};
render() {
return (
<div>
<Titles />
<Form getWeather={this.getWeather} />
<Weather />
</div>
);
}
}
export default App;
Form.js:
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>Get Weather</button>
</form>
);
}
}
export default Form;
有什么想法吗?感谢您的宝贵时间。
【问题讨论】:
-
你可以试试
e.target.value.element.city.value。我不知道这个 api 如何返回一个 json,但似乎函数看不到它。如果这不起作用,请尝试e.target.city.value。 -
你需要在你的构造函数中调用超级构造函数 - 将 props 传入你的构造函数并添加 super(props);。必须先完成超级调用,然后才能使用“this”。
标签: javascript reactjs