启动应用程序时更新上下文中的状态



所以基本上我已经有2个主要组件,家庭和前线(天气应用程序(。我使用地理位置,现在当我从主页路由到首页时,需要 2 秒才能从用户那里获取地理位置,所以我的首页加载了一些空信息,2 秒后我的页面更新数据。因此,我想在运行应用程序并且显示主页组件时获取并更新我的状态。

上下文:

import React, { createContext, useState, useEffect } from 'react';
import {promiseLocation} from '../components/Location'
import axios from 'axios'
const KEY = 'fdc0a9d5321ee73e70535ed7d7e052ce'
export const InitialWeatherContext = createContext();
const InitialWeatherContextProvider = props => {
const [initialWeather, setInitial] = useState({
city: null,
temp: null,
feels: null
});

useEffect(() => {
const fetchLocation = async () => {
const { coords } = await promiseLocation();
const response = await axios(
`https://api.openweathermap.org/data/2.5/weather?lat=${coords.latitude}&lon=${coords.longitude}&appid=${KEY}&units=metric`
);
setInitial({
city: response.data.name,
temp: response.data.main.temp,
feels: response.data.main.feels_like
});
};
fetchLocation();
}, []);
// ...

return (
<InitialWeatherContext.Provider value={{initialWeather}}>
{props.children}
</InitialWeatherContext.Provider>
);
};

export default InitialWeatherContextProvider

前面:

import React, {useContext} from 'react';
import { InitialWeatherContext } from '../context/InitialWeatherContext'
const Front =  () => {

const {initialWeather} = useContext(InitialWeatherContext)
console.log(initialWeather)
return (
<div className='front'>
<div className='date-city-data-wrap'>
<div className='date-name'>
<p className='date'>March 13</p>
<h1 className='city'>{initialWeather.city}</h1>
</div>
<div className='data'>
<div className='temp'>
<h1>Helo</h1>
<p></p>
</div>
<div className='data-info-wrap rain'>
<div className='icon rain-icon'>
<i className="fas fa-ad"></i>
<p>humidity</p>
</div>
<h1>40%</h1>
</div>
<div className='data-info-wrap wind'>
<div className='icon wind-icon'>
<i className="fas fa-ad"></i>
<p>humidity</p>
</div>
<h1>8 km/h</h1>
</div>
<div className='data-info-wrap humidity'>
<div className='icon humidity-icon'>
<i className="fas fa-ad"></i>
<p>humidity</p>
</div>
<h1>5%</h1>
</div>
<div className='data-info-wrap humidity'>
<div className='icon humidity-icon'>
<i className="fas fa-ad"></i>
<p>humidity</p>
</div>
<h1>5%</h1>
</div>
</div>
</div>
</div>
)
}
export default Front

您可以在提供程序本身中运行useEffect

const InitialWeatherContextProvider = props => {
const [initialWeather, setInitial] = useState({
city: null,
temp: null,
feels: null
});
useEffect(() => {
const fetchLocation = async () => {
const { coords } = await promiseLocation();
const response = await axios(
`https://api.openweathermap.org/data/2.5/weather?lat=${coords.latitude}&lon=${coords.longitude}&appid=${KEY}&units=metric`
);
setInitial({
city: response.data.name,
temp: response.data.main.temp,
feels: response.data.main.feels_like
});
};
fetchLocation();
}, []);
// ...
return (
<InitialWeatherContext.Provider value={{ initialWeather, fillData }}>
{props.children}
</InitialWeatherContext.Provider>
);
};

相关内容

  • 没有找到相关文章

最新更新