API链接ReactJS上的变量不会更新

问题描述 投票:0回答:1

我在更新API链接上的变量时遇到问题。因此,这应该可以使该API链接的起始坐标为0,0(或者在最佳情况下,它首先应显示geonavigator窗口,接受后应为您的坐标显示天气,然后在该位置搜索另一个城市同一地点应该显示被搜索城市的天气,但仍然不知道该怎么做),这部分有效,但是在搜索栏上搜索另一个城市之后,API链接上的坐标(coordinates.lat和ordinates.lng)应更改为屏幕上应显示搜索到的城市坐标和天气变化,但是此部分不起作用。可能有点用,因为当我在返回<p>Latitude: {coordinates.lat}</p> <p>Longtitude: {coordinates.lng}</p>后显示城市时,每次搜索任何城市时,coordinates.lat和坐标.lng上的值似乎都在变化,但是天气完全没有变化,但仍显示为0 ,0坐标。很抱歉我的代码混乱,但我仍在学习。我也在说的第一个api链接是const api = ${proxy}https://api.darksky.net/forecast/1539bbb708779eef3993021296196cb2/${coordinates.lat},${coordinates.lng}

    import React, { useEffect, useState, } from "react";
import "./PogodaL.css";
import "./PogodaS.css";
import "./PogodaP.css";
import Skycons from "react-skycons"; 
import "./App.css";
import lupa from "./lupa.png";
import PlacesAutocomplete,{
  geocodeByAddress,
  getLatLng
} from "react-places-autocomplete";



export function App2() {
  const [state, setState] = useState({
    long: null,
    lat: null,
    precipProbability: "",
    temperatureDegree: 0,
    locationTimezone: "",
    minimalna: 0,
    maksymalna: 0,
    icons: ""
  });
  const [state2, setState2] = useState({
    long: null,
    lat: null,
    precipProbability: "",
    temperatureDegree: 0,
    locationTimezone: "",
    minimalna: 0,
    maksymalna: 0,
    icons: ""
  });

  const [state3, setState3] = useState({
    long: null,
    lat: null,
    precipProbability: "",
    temperatureDegree: 0,
    locationTimezone: "",
    minimalna: 0,
    maksymalna: 0,
    icons: ""
  });

  const [state4, setState4] = useState({
    long: null,
    lat: null,
    precipProbability: "",
    temperatureDegree: 0,
    locationTimezone: "",
    minimalna: 0,
    maksymalna: 0,
    icons: ""
  });

  const [address, setAddress] = useState(""); /* here is the start of defining variables */
  const [coordinates, setCoordinates] = useState({ 
      lat: 0, 
      lng: 0});

  const handleSelect = async (value) => {
      const results = await geocodeByAddress(value);
      const latLng = await getLatLng(results[0]);
      setAddress(value);
      setCoordinates(latLng);
  }


  useEffect(() => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(position => {
        const lat = position.coords.latitude;
        const long = position.coords.longitude;
        setState({
          ...state,
          lat,
          long
        });

        const proxy = "https://cors-anywhere.herokuapp.com/";
        const api = `${proxy}https://api.darksky.net/forecast/1539bbb708779eef3993021296196cb2/${coordinates.lat},${coordinates.lng}`;  /* here is that API Link*/

        fetch(api)
          .then(response => {
            return response.json();
          })
          .then(data => {
            console.log(data);
            const { temperature, precipProbability, icon } = data.currently;

            const celcjusz = ((temperature - 32) * 5) / 9;

            const { temperatureLow } = data.daily.data[1];
            const celcjusz1 = ((temperatureLow - 32) * 5) / 9;

            const { temperatureMax } = data.daily.data[1];
            const celcjusz2 = ((temperatureMax - 32) * 5) / 9;

            setState({
              ...state,

              temperatureDegree: Math.floor(celcjusz),
              locationTimezone: data.timezone,
              minimalna: Math.floor(celcjusz1),
              maksymalna: Math.floor(celcjusz2),
              precipProbability: precipProbability.toString().replace(/0.0/g, '').replace(/0./g,''), 
              icons: icon.replace(/-/g, "_").toUpperCase() 
            });

          });
          const apiL = `${proxy}https://api.darksky.net/forecast/1539bbb708779eef3993021296196cb2/50,23` ;
          fetch(apiL)
          .then(response => {
            return response.json();
          })
          .then(data => {
            console.log(data);
            const { temperature, precipProbability, icon } = data.currently;

            const celcjusz = ((temperature - 32) * 5) / 9;

            const { temperatureLow } = data.daily.data[1];
            const celcjusz1 = ((temperatureLow - 32) * 5) / 9;

            const { temperatureMax } = data.daily.data[1];
            const celcjusz2 = ((temperatureMax - 32) * 5) / 9;

            setState2({
              ...state2,
              precipProbability: precipProbability.toString().replace(/0.0/g, '').replace(/0./g,''), 
              temperatureDegree: Math.floor(celcjusz),
              locationTimezone: data.timezone,
              minimalna: Math.floor(celcjusz1),
              maksymalna: Math.floor(celcjusz2),
              icons: icon.replace(/-/g, "_").toUpperCase()            
            });         
          });

          const apiS = `${proxy}https://api.darksky.net/forecast/1539bbb708779eef3993021296196cb2/52.50,13.28` ;
          fetch(apiS)
          .then(response => {
            return response.json();
          })
          .then(data => {
            console.log(data);
            const { temperature, precipProbability, icon } = data.currently;

            const celcjusz = ((temperature - 32) * 5) / 9;

            const { temperatureLow } = data.daily.data[1];
            const celcjusz1 = ((temperatureLow - 32) * 5) / 9;

            const { temperatureMax } = data.daily.data[1];
            const celcjusz2 = ((temperatureMax - 32) * 5) / 9;

            setState3({
              ...state3,
              precipProbability: precipProbability.toString().replace(/0.0/g, '').replace(/0./g,''), 
              temperatureDegree: Math.floor(celcjusz),
              locationTimezone: data.timezone,
              minimalna: Math.floor(celcjusz1),
              maksymalna: Math.floor(celcjusz2),
              icons: icon.replace(/-/g, "_").toUpperCase()            
            });         
          });
          const apiP = `${proxy}https://api.darksky.net/forecast/1539bbb708779eef3993021296196cb2/40.69,-74.11`;
          fetch(apiP)
          .then(response => {
            return response.json();
          })
          .then(data => {
            console.log(data);
            const { temperature, precipProbability, icon } = data.currently;

            const celcjusz = ((temperature - 32) * 5) / 9;

            const { temperatureLow } = data.daily.data[1];
            const celcjusz1 = ((temperatureLow - 32) * 5) / 9;

            const { temperatureMax } = data.daily.data[1];
            const celcjusz2 = ((temperatureMax - 32) * 5) / 9;

            setState4({
              ...state4,
              precipProbability: precipProbability.toString().replace(/0.0/g, '').replace(/0./g,''), 
              temperatureDegree: Math.floor(celcjusz),
              locationTimezone: data.timezone,
              minimalna: Math.floor(celcjusz1),
              maksymalna: Math.floor(celcjusz2),
              icons: icon.replace(/-/g, "_").toUpperCase()            
            });         
          });

      });
    }
  }, []);
  return (

    <div className="App">
      <div>
        <PlacesAutocomplete 

        value={address} 
        onChange={setAddress} 
        onSelect={handleSelect}
        >{({getInputProps, suggestions, getSuggestionItemProps, loading}) => (
        <div class="Search-Bar">
            <p>Latitude: {coordinates.lat}</p> {/* I display it there and it changed everytime I search for any city so this works there */} 
            <p>Longtitude: {coordinates.lng}</p>

            <input {...getInputProps({placeholder: "Wpisz lokalizację"})} />
            <button type="submit"><img src={lupa} /></button>


            {suggestions.map((suggestion) => {
                const style = {
                    backgroundColor: suggestion.active ? "#41b6e6" : "#e6eeff"
                }
               return ( <div {...getSuggestionItemProps(suggestion, { style })} class="Suggestion"> {suggestion.description} </div> 
               )
               }  
             )
            }

        </div> 
        )
        }


        </PlacesAutocomplete>
    </div>

      <div class="location">
  <h1 class="location-timezone"> {state.locationTimezone} </h1> </div>
       <div class="icon"> <Demo icons={state.icons} /> </div>

      <div class="temperature">
        <div class="degree-section">
          <span> {state.temperatureDegree}°C </span>
        </div>
        <div class="precipProbability">
          {"Szansa opadów: "}
          {state.precipProbability}{"% "}
        </div>
      </div>

      <div class="sekcja-jutro">
        <h1>Pogoda na Jutro: </h1>
      </div>

      <div class="minimalna">
        <span> Temperatura minimalna:</span>
        <h1 class="temperatura-minimalna"> {state.minimalna} </h1>
        <span> °C </span>
      </div>

      <div class="maksymalna">
        <span>Temperatura maksymalna:</span>
        <h1 class="temperatura-maksymalna"> {state.maksymalna}</h1>
        <span>°C</span>
      </div>


      <div class="locationL">
  <h1 class="location-timezoneL"> {state2.locationTimezone} </h1> </div>



      <div class="temperatureL">
        <div class="degree-sectionL">
        <div class="iconL"><Demo icons={state2.icons} />  </div>  
          <span> {state2.temperatureDegree}°C </span>
        </div>
        <div class="temperature-descriptionL">
          {"Szansa opadów: "}
          {state2.precipProbability}{"%"}
        </div>
      </div>  

      <div class="locationS">
  <h1 class="location-timezoneS"> {state3.locationTimezone} </h1> </div>      
      <div class="temperatureS">
        <div class="degree-sectionS">
        <div class="iconS"><Demo icons={state3.icons} />  </div>  
          <span> {state3.temperatureDegree}°C </span>
        </div>
        <div class="temperature-descriptionS">
          {"Szansa opadów: "}
          {state3.precipProbability}{"%"}
        </div>
      </div>  

      <div class="locationP">
  <h1 class="location-timezoneP"> {state4.locationTimezone} </h1> </div>      
      <div class="temperatureP">
        <div class="degree-sectionP">
        <div class="iconP"><Demo icons={state4.icons} />  </div>  
          <span> {state4.temperatureDegree}°C </span>
        </div>
        <div class="temperature-descriptionP">
          {"Szansa opadów: "}
          {state4.precipProbability}{"%"}
        </div>
      </div> 

    </div>





  );
}

class Demo extends React.Component {
  render() {
    return (
      <Skycons

        color="white"
        icon={this.props.icons} 
        autoplay={true}
        height="130"
      />
    );
  }
}
export default App2;
javascript reactjs api variables weather
1个回答
0
投票

这将在加载/安装组件时仅被调用一次

useEffect(() => {
     ...
},[]);

您可以将coordinates作为依赖项进行传递,因此只要coordinates发生更改,它将被调用

useEffect(() => {
     ...
},[coordinates]); 
© www.soinside.com 2019 - 2024. All rights reserved.