[英]React.JS, how to edit the response of a first API call with data from a second API call?
[英]Response from API returns data, state is undefined - React.JS
我有一个 REACT 组件:
import React from 'react';
import Weather from '../service/weatherAPI.js';
export default class DisplayWeather extends React.Component {
constructor(props){
super(props);
this.state = {
weatherData: []
}
this.getWeatherData = this.getWeatherData.bind(this);
}
componentDidMount(){
this.getWeatherData();
}
async getWeatherData(){
let data = await Weather(this.props.location)
this.setState({ weatherData: data});
console.log(this.state.weatherData)
}
此函数引用从另一个文件导出的函数,该文件使用 fetch 调用端点。 所有数据从我正在调用的端点正确返回。 但是,当尝试将此数据设置为状态时,我的数据未定义。
下面是我的 API 调用,以防万一我错过了这里的任何内容:
const Weather = (location) => {
fetch(url, {
Method: 'GET',
headers : {
'Accept': 'application/json'
},
})
.then((raw) => raw.json())
.then((response) => {
return response
})
}
export default Weather;
提前致谢。
你需要在你的天气函数中返回这样的承诺:
const Weather = (location) => {
return fetch(url, {
Method: 'GET',
headers : {
'Accept': 'application/json'
},
})
.then((raw) => raw.json())
.then((response) => {
return response
})
}
这样, await 就可以处理 Promise 而不仅仅是函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.