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