React - 如何使用已解决承诺中的数据设置状态

React - how to set state with the data from a resolved promise

我正在努力将我的数据从获取请求获取到我的容器状态

我的获取请求存储在 api.js 中,看起来像这样 - 它从常量中检索密钥,这很好:-

import { openWeatherKey } from './constants';

const getWeather = async() => {
    const base = "https://api.openweathermap.org/data/2.5/onecall";
    const query = `?lat=52.6&lon=-2.2&exclude=hourly,daily&appid=${openWeatherKey}`;

    const response = await fetch(base + query);
    const data = await response.json();

    return data;
}

export { getWeather };

我的容器是这样的:-

import React, { Component } from "react";
import './weather.css';
import { getWeather } from './api';

class Spy extends Component {

    constructor() {
        super()
        this.state = {test(){return "this is a test"}}
    }

    render() {
        return (
            <div id="spy-weather" className="app-border">
                <h3 className="spy-name">Weather at { this.props.location } {this.state.test()}</h3> 
            </div>
        )
    }
}

(() => {
    getWeather().then(data => {
        console.log(data);  
    })
})();  

export { Spy as Weather };

我有一个 IIFE,它发出请求并将结果打印到控制台。您可以在 class 声明和上面的导出语句之间看到。

这是控制台的结果 - 请求工作正常

{lat: 52.6, lon: -2.2, timezone: "Europe/London", timezone_offset: 3600, current: {…}}
current: {dt: 1594401262, sunrise: 1594353486, sunset: 1594412995, temp: 289.05, feels_like: 286.49, …}
lat: 52.6
lon: -2.2
timezone: "Europe/London"
timezone_offset: 3600
__proto__: Object

我无法做到的是使用已解决承诺中的数据设置状态。我尝试了各种方法,包括我看到的一些无效的解决方案。

如何在容器中放置和 运行 函数,然后使用数据更新状态?

你可能会说,我对 React 很陌生。

衷心感谢,

菲尔

在基于 class 的组件中,称为 componentDidMount 的生命周期方法用于在组件安装后执行某些操作。在您的情况下,将 IIFE 中的代码移动到 componentDidMount 方法中。

state 对象中创建一个 属性 来保存天气数据。或者,您还可以在 state 对象中创建一个 属性 来保存从 API.

获取数据期间可能发生的任何错误消息
this.state = {
   weatherData: null,
   error: ''
};

然后从 componentDidMount() 生命周期方法

调用 getWeather() 函数
componentDidMount() {
    getWeather()
      .then(data => {
        this.setState({ weatherData: data });
      })
      .catch(error => this.setState({ error: error.message }));
}

在功能组件中,useEffect hook is used to perform any side-effect like fetching data from an API. State in functional components is saved using useState钩子。

如果您使用功能组件,那么您的代码将如下所示:

const [weatherData, setWeatherData] = useState(null);
const [error, setError] = useState(null);

useEffect(() => {
    getWeather()
      .then(data => {
          setWeatherData(data);
      })
      .catch(error => setError(error.message));
}, []);
this.state = {test(){return "this is a test"}}

这是状态管理的无效结构,正确的方法

getWeather().then(data => {
        console.log(data);
        this.setState({ weatherData: data });
})

状态结构太

state = {
  someProperty: value,
  someArray: [],
  weatherData: {}
}