繁体   English   中英

如何在 React js 中使用全局变量?

[英]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;

我想在返回函数中使用一个名为 temp 的变量。 但我不确定如何在 React 中声明全局变量。 我真的很感激任何帮助。

temp声明为状态变量,您可以将其用作返回方法。

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;

不鼓励在您的示例等上下文中使用自定义全局变量。 您的情况类似于状态处理。 您可以创建一个可以导入和使用的单独模块。 还要在状态处理的情况下进行修改。

import {temp} from './myglobals'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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