为什么我首先在控制台中获取 Null,然后才获取值(react.js)
2022-07-30
1019
应该获取纬度和经度的值,但由于某种原因,我得到的初始状态是“null”,然后同时在控制台中获得另一个包含数据的响应。
如图所示,它首先返回它为 null,然后(无需刷新或任何操作)返回值。 下面是我的代码
这是我获取 coords 值的地方(来自 react 库)
//Getting geolocation
const {coords, isGeolocationAvailable , isGeolocationEnabled} = useGeolocated({
positionOptions: {
enableHighAccuracy: false
},
userDecisionTimeout: 5000,
})
//Setting Latitude and Longitude states
useEffect (() => {
if (coords) {
setLatitiude(coords.latitude)
setLongitude(coords.longitude)
}
}, [coords]);
//Fetch data from API
useEffect (() => {
console.log(`Latitude = ${latitude} and Longitude = ${longitude}`)
//Function to call API
const weatherForecast = async () => {
await axios.get(`${API_ENDPOINT}lat=${latitude}&lon=${longitude}&exclude=hourly,daily&appid=${API_KEY}`)
.then((res) => {
setWeatherDetails(res.data)
})
}
if(latitude !== null & longitude !== null) {
weatherForecast()
} else {
console.log("Error getting data")
}
}, [latitude , longitude]);
当我第一次 npm 启动前端时,它可以正常工作,但是当我刷新时,就会发生这种情况。知道发生了什么吗?为什么看起来像是重新渲染了三次才得到结果。由于这种行为,我的 API 无法获取所需的数据并返回错误。
3个回答
您第一次获得
null
值是因为您在
coords
数据加载之前就记录了它。
请尝试这个
//Getting geolocation
const {coords, isGeolocationAvailable , isGeolocationEnabled} = useGeolocated({
positionOptions: {
enableHighAccuracy: false
},
userDecisionTimeout: 5000,
})
//Setting Latitude and Longitude states
useEffect (() => {
if (coords) {
setLatitiude(coords.latitude)
setLongitude(coords.longitude)
}
}, [coords]);
//Function to call API
const weatherForecast = async () => {
await axios.get(`${API_ENDPOINT}lat=${latitude}&lon=${longitude}&exclude=hourly,daily&appid=${API_KEY}`)
.then((res) => {
setWeatherDetails(res.data)
}).catch(() => {
console.log("Error getting data")
})
}
//Fetch data from API
useEffect (() => {
if(latitude !== null && longitude !== null){
console.log(`Latitude = ${latitude} and Longitude = ${longitude}`)
weatherForecast()
}
}, [latitude , longitude]);
Sanket Shah
2022-07-30
组件渲染后会调用 useEffect。因此第一次,纬度和经度(可能 cords 为空)。
第二次我猜 cords 存在并设置了 long 和 lat。这会触发重新渲染,因为您的第二个 useEffect 在其依赖项中拥有它们。数组
第三次渲染后,long 和 lat 被设置。
在 React 中,多次重新渲染是很常见的。
Erik
2022-07-30
在实际获取值之前,只需补充说明两次渲染(实际上应该是一次)的原因:默认情况下启用的 React StrictMode 将导致 useEffect 运行两次,但仅在开发模式下运行,而不管初始渲染后的依赖项如何,以确保您了解所有可能的副作用,并且清理处理程序按预期工作。您可以在 此处 找到更多信息。
Dorji Tshering
2022-07-30