Javascript API的响应返回数据,状态未定义-React.JS

Javascript API的响应返回数据,状态未定义-React.JS,javascript,reactjs,Javascript,Reactjs,我有一个反应组件: 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.getWe

我有一个反应组件:

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
  })
}

通过这种方式,“等待”正在处理承诺,而不仅仅是函数。

您必须使用your fetch函数的承诺。当您检查网络日志时,请求通过了吗?您需要转换响应并将其分配到您的状态您可以显示完整的代码示例吗?@wentjun是的,我得到了预期的响应。