简体   繁体   中英

How to use global variable in React js?

import React, {useEffect, useState } from 'react';
import axios from 'axios';

function Weather(){

useEffect(()=>{
    const apiCall= async ()=>{
        var appid="";
        const resp=await axios.get(`http://api.openweathermap.org/data/2.5/weather?q=seoul&appid=${appid}`);
        console.log(resp.data);

        var temp=String((resp.data.main.temp-273)).substring(0,4);
    };
    apiCall();
},[]);

return(
    <div>
        <div className="displayTime">{temp}</div>
    </div>
);
}
export default Weather;

I want to use a variable called temp in the return function. But I am not sure how to declare global variables in React. I would be truly grateful for any help.

Declare temp as the state variable and you can use it the return method.

import React, {useEffect, useState } from 'react';
import axios from 'axios';

function Weather(){

const [temp,setTemp] = useState("");
useEffect(()=>{
    const apiCall= async ()=>{
        var appid="";
        const resp=await axios.get(`http://api.openweathermap.org/data/2.5/weather?q=seoul&appid=${appid}`);
        console.log(resp.data);

        setTemp(String((resp.data.main.temp-273)).substring(0,4));
    };
    apiCall();
},[]);

return(
    <div>
        <div className="displayTime">{temp}</div>
    </div>
);
}
export default Weather;

The use of self defined globals in context like your example is discouraged. Your case is similar to state handling. You might create a separate module that you can import and use. Also modify in case of state handling.

import {temp} from './myglobals'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM