我正在使用React构建一个通用的天气网络应用程序。现在我只是想得到一个城市的天气数据。不执行任何动态操作)并将其记录在控制台中。
我正在使用OpenWeatherMap API。
但是,无论何时调用API,都会出现以下错误:
以前,我曾尝试使用AccuWeather API,但它也出现了相同的错误。
但是,如果我在React中调用componentDidMount()函数中的API,它可以很好地获取数据。当我尝试在表单提交时获取天气数据时,就会出现麻烦。
下面是我的主要应用程序代码:
weatherData = async function() {
try {
const resp = await fetch('https://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=APP-ID');
const data = await resp.json();
console.log(data);
} catch (err) {
console.log(err)
}
}
render() {
return (
<div>
<Title />
<Form loadWeather={this.weatherData} />
</div>
)
}
}这是反应部分:
import React from 'react';
import './Form.css';
const Form = (props) => {
return (
<form onSubmit = {props.loadWeather}>
<input className='input' type='text' name='city' placeholder='Enter City'></input>
<input className='input' type='text' name='country' placeholder='Enter Country'></input>
<button className='button'>Get Weather!</button>
</form>
)
}发布于 2020-03-27 16:47:33
您需要完全致力于一种方法,或者使用另一种方法:
基本React.Component类示例:
constructor(props) {
//...
this.weatherData = this.weatherData.bind(this);
}
async weatherData() {/* your code */}或者,使用冷静的方法:
weatherData = () => {/* ... */}您的镇定是分配一个function(),它重新绑定this的上下文。您需要指定一个箭头函数() => {},以保留this,以免发现自己丢失了this。
解决这种绑定性问题的最好方法是采用功能方法:
function WeatherThing() {
const weatherData = async () => {
const weatherInfo = await weatherDataFetch();
}
return (<div onClick={weatherData}>Do Weather stuff</div>);
}我建议阅读有关反应钩的内容,以使您的代码更具可读性。
发布于 2019-06-29 15:19:17
为了在子组件中执行,需要将weatherData绑定到父组件。要使其工作,只需将其绑定到第一个组件的构造函数:
this.weatherData = this.weatherData.bind(this)作为:
constructor(props) {
super(props)
this.state = {
//blabla
},
this.weatherData = this.weatherData.bind(this)
}发布于 2021-05-15 09:14:15
我更改了dev env的主机名,并遇到了同样的问题。
如果重新启动浏览器或机器,问题就会消失。
https://stackoverflow.com/questions/56818582
复制相似问题