Fetch/TemplateLiteral 在 React 中传递数据时出现问题

Fetch/TemplateLiteral issue passing Data in React

我正在构建一个天气应用程序,它可以从浏览器中提取位置和日期数据。获取位置数据后,该应用会呈现一个 header,根据纬度和月份告诉您季节,为您提供拉取位置的 GoogleMap window,并从 http://api.weatherapi.com/v1 获取数据获得 5 天的预报。我专门为这个项目使用 prop-drilling 来展示对单向数据流的理解,所以我试图避免为这个特定的应用程序使用挂钩。我还为警报设置了条件渲染。

一切正常!!! 我的 lat/lon 正在正确拉动并保存在我的状态 object 中,正如我最初从天气 api 获取天气预报数据的 "Chicago" 请求一样。我在 App 中有两个组件:一个显示季节 header 的 SeasonDisplay 和一个将必要的纬度和经度坐标作为道具向下传递的 LocationData 组件。 *** SeasonDisplay 按预期工作。

import React from "react";
import SeasonDisplay from './SeasonDisplay';
import './SeasonDisplay.css';
import Loader from './loader.js';
import LocationData from "./LocationData";
import "./App.css";
class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            lat: null,
            lon: null,
            mapData: [],
            weatherForecast: [],
            errorMessage: null
        }
    }
    async componentDidMount() {
        await window.navigator.geolocation.getCurrentPosition(
            (position) => {
                this.setState({ lat: position.coords.latitude });
                this.setState({ lon: position.coords.longitude });
            },
            (error) => this.setState({ errorMessage: error.message })
        );
        const response = await fetch(`http://api.weatherapi.com/v1/forecast.json?key=///apiKey///&q="Chicago"&days=5`)
        const data = await response.json();
        console.log(data);
        this.setState({ weatherForecast: data.forecast.forecastday });
    }
    renderContent() {
        if(this.state.errorMessage || !this.state.lat) {
            return <h2>Error: {this.state.errorMessage}</h2>;
        } else if (!this.state.errorMessage && this.state.lat) {
            return (
                    <div id="container">
                        <div>
                            <SeasonDisplay
                                lat={this.state.lat}
                                lon={this.state.lon}
                            />
                        </div>
                        <div id="locationData">
                            <LocationData
                                lat={this.state.lat}
                                lon={this.state.lon}
                                weatherForecast={this.state.weatherForecast}
                            />
                        </div>
                    </div>
            );
        }
        return (
            <div>
                <Loader message="Waiting on You..." />
            </div>
        )
    };
    render() {
        return (
            <div id="container">
                {this.renderContent()}
            </div>
        )
    }
}
export default App;

在我的 LocationData 组件中,我采用 lat/lon 道具并将它们传递给另外两个组件 GoogleApiWrapper 和 WeatherCard。

*** GoogleApiWrapper 按预期工作,所以我知道我正在将我的道具正确传递给 LocationData 组件,并且 App 的状态正在向下传递数据,而不是 null 或 undefined。

import React from "react";
import GoogleApiWrapper from "../APIs/mapsAPI";
import WeatherCard from "./WeatherCard";
import "./LocationData.css";
const LocationData = props => {
  return (
    <div className="locationData">
      <GoogleApiWrapper
        lat={props.lat}
        lon={props.lon}
      />
      <WeatherCard
        lat={props.lat}
        lon={props.lon}
        weatherForecast={props.weatherForecast}
      />
    </div>
  );
};
export default LocationData;

从这里开始,lat/lon 道具将传递到 WeatherCard 组件,该组件将 weatherForecast 索引数据映射到在地图旁边呈现的卡片。 (在我更改卡流之前解决这个问题)。作为确保道具通过的测试,我将纬度和经度添加到天气卡中,以便我可以在 ReactDevTools/Comonents 中看到数据,并且 Lat/Lon 数据在那里。

所以一切正常。

****问题来了****

我无法让 lat/lon 状态值在提取请求中正确传递。我曾多次尝试使用模板文字,但 api 文档令人困惑。我之前使用过 axios,但删除了它,因为在尝试传递 key/value 参数时,我一直在获取像南美洲的 Null 或挪威的 Lat 这样的城市.....

文档说将其传递为:

Latitude and Longitude (Decimal degree) e.g: q=48.8567,2.3508

所以我尝试通过各种版本的

const response = await fetch(`http://api.weatherapi.com/v1/forecast.json?key=///apiKey///&q=${this.props.lat},${this.props.lon}&days=5`)

使其位置特定于最终用户,但它不断传递来自厄瓜多尔 Null 的返回结果... 所以我的纬度值是在设置位置数据之前传入的,尽管在 ReactDevTools 中,纬度和经度都正确显示。

如何传递 lat/lon 值来获取相应位置的预测数据???

此外,这是我的第一个 post,所以请耐心等待我尝试遵循 over-sharing 风险的格式... 任何反馈都是优质的。

设置状态主要是异步的,所以如果你想使用新设置的状态值,你会考虑在 setState 的回调中这样做。还要避免多次 setState 调用,你可以将它们合并为一个:

  async componentDidMount() {
    await window.navigator.geolocation.getCurrentPosition(
      position => {
        const { latitude, longitude } = position.coords;
        this.setState(
          {
            lat: latitude,
            lon: longitude,
          },
          async () => {
            // use calback here
            const response = await fetch(
              `http://api.weatherapi.com/v1/forecast.json?key=///apiKey///${this.state.lat},${this.state.lon}&days=5`
            );
            const data = await response.json();
            console.log(data);
            this.setState({
              weatherForecast: data.forecast.forecastday,
            });
          }
        );
      },
      error =>
        this.setState({
          errorMessage: error.message,
        })
    );
  }