如何在ReactJS中的EventListener之后仍然定义变量?

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

我的代码中的变量“图标”有问题。它是在EventListener范围中初始化和定义的,但是在该范围之后没有定义,因此在尝试编译时出现错误。我真的不知道如何在reactJS中创建全局变量,并且在搜索它之后似乎不建议这样做。那么,有没有一种方法可以使该变量在EventListener范围之外工作,以便类“ Demo”可以使用它?

import React from 'react';
import logo from './logo.png';
import './App.css';
import Skycons from 'react-skycons';

function App() {
  return (
    <div className="App">

        <img src={logo} className="App-logo" alt="logo" />

        <div class="location"> 
    <h1 class="location-timezone"> Lokalizacja </h1>
    <Demo />    
</div>

<div class="temperature">
    <div class="degree-section">

    <h2 class="temperature-degree"> Brak </h2>
        <span> °C </span>
    </div>
    <div class="temperature-description"> Brak </div>

</div>

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

<div class="minimalna">
    <span>Minimalna:</span>
    <h1 class="temperatura-minimalna"> Brak </h1>
    <span> °C </span> 
</div>

<div class="maksymalna">
    <span>Maksymalna:</span>
    <h1 class="temperatura-maksymalna"> Brak </h1>
    <span>°C</span>
</div>

    </div>


  );
}

window.addEventListener('load',()=> {
    let long;
    let lat;
    let temperatureDescription = document.querySelector(".temperature-description");
    let temperatureDegree = document.querySelector(".temperature-degree");
    let locationTimezone = document.querySelector(".location-timezone");
    let minimalna = document.querySelector(".temperatura-minimalna");
    let maksymalna = document.querySelector(".temperatura-maksymalna");

    if(navigator.geolocation){
            navigator.geolocation.getCurrentPosition(position =>{
                long = position.coords.longitude;
                lat = position.coords.latitude;

                const proxy = "https://cors-anywhere.herokuapp.com/";
                const api = `${proxy}https://api.darksky.net/forecast/1539bbb708779eef3993021296196cb2/${lat},${long}`;

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

                var icons;  //there is initialized
                icons = icon.replace(/-/g, "_").toUpperCase();  //there is defined
                console.log(icons); //There I make it display in console so I see that it works as it should

                temperatureDegree.textContent = temperature;
                let celcjusz = (temperature - 32) * 5/9;
                temperatureDegree.textContent = Math.floor(celcjusz);
                temperatureDescription.textContent = summary;
                locationTimezone.textContent = data.timezone;

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

                const {temperatureMax} = data.daily.data[1];
                maksymalna.textContent = temperatureMax;          
                let celcjusz2 = (temperatureMax - 32) * 5/9;
                maksymalna.textContent = Math.floor(celcjusz2);
            });
            });
        }
    });
      class Demo extends React.Component {
        render () {
          return (
            <Skycons 
              class="icon"  
              color='white' 
              icon={icons}  //There I make display icon as anything is in "icons" variable but after compiling I got error that icons is not defined
              autoplay={true}
              height="130"                 
            />
          )
        }
      }
export default App;
javascript reactjs variables scope global-variables
2个回答
0
投票

我不知道您是否正确使用了'load'事件,我认为您可以将监听器放入应用程序中的DidMount或useEffect中,并使用应用程序的状态,并将其作为参数传递给组件Demo :


0
投票

欢迎使用stackoverflow!

您发现您不应创建全局变量。 (通常,这不是一个好主意)

您正在使用可以使用function App()的功能组件React Hooks

您可以使用useEffect钩子替换window.onloaduseState以使组件具有内部状态。

类似这样的东西:

import React, { useEffect, useState } from "react";
import logo from './logo.png';
import './App.css';
import Skycons from 'react-skycons';    
function App() {
  const [state, setState] = useState({
    long: null,
    lat: null,
    temperatureDescription: "",
    temperatureDegree: 0,
    locationTimezone: "",
    minimalna: 0,
    maksymalna: 0,
    icons: ""
  });

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

        const proxy = "https://cors-anywhere.herokuapp.com/";
        const api = `${proxy}https://api.darksky.net/forecast/1539bbb708779eef3993021296196cb2/${lat},${long}`;

        fetch(api)
          .then(response => {
            return response.json();
          })
          .then(data => {
            console.log(data);
            const { temperature, summary, 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,
              temperatureDescription: summary,
              temperatureDegree: Math.floor(celcjusz),
              locationTimezone: data.timezone,
              minimalna: Math.floor(celcjusz1),
              maksymalna: Math.floor(celcjusz2),
              icons: icon.replace(/-/g, "_").toUpperCase() //there is defined
            });
          });
      });
    }
  }, []);

  return (
    <div className="App">
      <img src={logo} className="App-logo" alt="logo" />

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

      <div class="temperature">
        <div class="degree-section">
          <h2 class="temperature-degree"> Brak </h2>
          <span> {state.temperatureDegree}°C </span>
        </div>
        <div class="temperature-description">
          {" "}
          {state.temperatureDescription}{" "}
        </div>
      </div>

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

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

      <div class="maksymalna">
        <span>Maksymalna:</span>
        <h1 class="temperatura-maksymalna"> Brak </h1>
        <span>{state.maksymalna}°C</span>
      </div>
    </div>
  );
}

class Demo extends React.Component {
  render() {
    return (
      <Skycons
        class="icon"
        color="white"
        icon={this.props.icons} //There I make display icon as anything is in "icons" variable but after compiling I got error that icons is not defined
        autoplay={true}
        height="130"
      />
    );
  }
}
export default App;

我没有测试它是否运行,但从理论上讲,这应该是您的目标。请不要在渲染后运行useEffect。这意味着如果您愿意,可以显示加载的动画或文本,直到long!=null为止,以获得更好的用户体验。

© www.soinside.com 2019 - 2024. All rights reserved.