Геолокация получаю после отрисовки компонента в react, как исправить?
есть вот этот код компонента:
export default function App() { const [userLocation, setUserLocation] = useState(null) const [appState, getData] = useState({ loading: false, data: { name: null, country: null, temp: null, humidity: null, speed: null, }, }) navigator.geolocation.getCurrentPosition(position => { const { latitude, longitude } = position.coords setUserLocation({ latitude, longitude }) }) useEffect(() => { getData({ lodaing: true, data: appState.data }) const API = '***' const url = `https://api.openweathermap.org/data/2.5/weather?lat=${userLocation.lat}&lon=${userLocation.lon}&appid=${API}&units=metric` fetch(url) .then(res => res.json()) .then(res => { console.log(res) getData({ loading: false, data: { name: res.name, country: res.sys.country, temp: res.main.temp, humidity: res.main.humidity, speed: res.wind.speed, }, }) }) }, [getData]) return ( *** ) } |
export default function App() { const [userLocation, setUserLocation] = useState(null) const [appState, getData] = useState({ loading: false, data: { name: null, country: null, temp: null, humidity: null, speed: null, }, }) navigator.geolocation.getCurrentPosition(position => { const { latitude, longitude } = position.coords setUserLocation({ latitude, longitude }) }) useEffect(() => { getData({ lodaing: true, data: appState.data }) const API = '***' const url = `https://api.openweathermap.org/data/2.5/weather?lat=${userLocation.lat}&lon=${userLocation.lon}&appid=${API}&units=metric` fetch(url) .then(res => res.json()) .then(res => { console.log(res) getData({ loading: false, data: { name: res.name, country: res.sys.country, temp: res.main.temp, humidity: res.main.humidity, speed: res.wind.speed, }, }) }) }, [getData]) return ( *** ) }
все пишет что у стейта нет latitude и longitude . + проверьте правильно ли я тут наделал.
Дополнительно:
useEffect(() => { // ... }, [getData]) |
useEffect(() => { // ... }, [getData])
getData - функция, которую возвращает useState - никогда не меняется, это есть где-то в доке реакта. Если вам нужно реагировать на изменение данных - замените на appState
И в самом эффекте добавьте условие, чтоб отсеивать рендер без данных:
useEffect(() => { if (!appState) return; // ... }, [appState]) |
useEffect(() => { if (!appState) return; // ... }, [appState])
Yukan Mukimura быть может вычислить геолокацию как изначальное состояние? Или вообще как константу? И запрос к апи сделать с пустыми зависимостями, чтоб 1 раз брался? Как мне показалось, ты хочешь написать код именно с такой функциональностью. Если есть замысел перерисовок, связанных с изменением локации, это не подойдет.
Должно быть так, вероятно:
useEffect(() => { if (!userLocation) return; getData({ lodaing: true, data: appState.data }) const API = '***' const url = `https://api.openweathermap.org/data/2.5/weather?lat=${userLocation.lat}&lon=${userLocation.lon}&appid=${API}&units=metric` fetch(url) .then(res => res.json()) .then(res => { console.log(res) getData({ loading: false, data: { name: res.name, country: res.sys.country, temp: res.main.temp, humidity: res.main.humidity, speed: res.wind.speed, }, }) }) }, [userLocation]) |
useEffect(() => { if (!userLocation) return; getData({ lodaing: true, data: appState.data }) const API = '***' const url = `https://api.openweathermap.org/data/2.5/weather?lat=${userLocation.lat}&lon=${userLocation.lon}&appid=${API}&units=metric` fetch(url) .then(res => res.json()) .then(res => { console.log(res) getData({ loading: false, data: { name: res.name, country: res.sys.country, temp: res.main.temp, humidity: res.main.humidity, speed: res.wind.speed, }, }) }) }, [userLocation])
Опишите проблему, и специалист поможет с настройкой, исправлением ошибки или доработкой сайта. Подберём понятный план работ без лишней переписки.
Пока нет других ответов. Будьте первым, кто поможет автору.
Ответить на вопрос
Для того чтобы получить геолокацию после отрисовки компонента в React, можно воспользоваться хуком useEffect.
Ниже приведен пример кода на React, который демонстрирует получение геолокации после отрисовки компонента:
import React, { useEffect, useState } from 'react'; const GeolocationComponent = () => { const [latitude, setLatitude] = useState(null); const [longitude, setLongitude] = useState(null); useEffect(() => { navigator.geolocation.getCurrentPosition((position) => { setLatitude(position.coords.latitude); setLongitude(position.coords.longitude); }); }, []); return ( <div> <p>Latitude: {latitude}</p> <p>Longitude: {longitude}</p> </div> ); }; export default GeolocationComponent;
В этом примере мы используем хук useEffect для вызова функции getCurrentPosition() объекта navigator.geolocation после отрисовки компонента. При успешном получении геолокации, мы обновляем состояния latitude и longitude с помощью функций setLatitude и setLongitude соответственно.
Помните, что для использования геолокации в браузере пользователь должен дать разрешение на доступ к его местоположению. В случае отказа доступа к геолокации, можно предусмотреть соответствующую обработку ошибки.