[英]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.我想在返回函数中使用一个名为 temp 的变量。 But I am not sure how to declare global variables in React.
但我不确定如何在 React 中声明全局变量。 I would be truly grateful for any help.
我真的很感激任何帮助。
Declare temp as the state variable and you can use it the return method.将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;
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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.