在useEffect (React)中获取未定义的值



下面的函数获取用户的当前位置:

const getCurrentLocation = () => {
fetch("https://ipinfo.io/json?token=$TOKEN")
.then((response) => response.json())
.then((jsonResponse) => {
console.log(jsonResponse)
return jsonResponse;
});
};
useEffect(() => {
console.log(getCurrentLocation());
}, []);  

登录useEffect显示undefined,它首先出现在控制台中,然后jsonResponse在控制台中显示相应的对象。为什么?

getCurrentLocation不返回任何东西,这就是为什么你得到undefined

此外,fetch返回一个Promise,它是异步的,这意味着你不能立即得到结果,你必须传递一个回调到then来获得结果,当它是可用的。

const getCurrentLocation = () => {
return fetch("https://ipinfo.io/json?token=$TOKEN")
.then(response => response.json());
};
useEffect(() => {
getCurrentLocation()
.then(location => console.log(location));
}, []);  

getCurrentLocation函数没有返回任何内容。尝试保存当前状态下的位置,以便在需要时访问它:

const [currentLocation, setCurrentLocation] = useState(null);
const getCurrentLocation = () => {
fetch("https://ipinfo.io/json?token=$TOKEN")
.then((response) => response.json())
.then((jsonResponse) => {
setCurrentLocation(jsonResponse); // <- save the location in state
});
};
useEffect(() => {
getCurrentLocation();
}, []);
return <div>{currentLocation}</div>

如果您需要useEffect中的位置,您可以这样做:

useEffect(() => {
if (currentLocation !== null) {
// ...
}
}, [currentLocation])

你可以简单地使用async/await来获得响应,看看这个:

const getCurrentLocation = async () => {
const result = await fetch("https://ipinfo.io/json?token=$TOKEN");
return result.json();
};

const handleGetLocation = async () => {
const result = await getCurrentLocation();
console.log(result);
};
useEffect(() => {
handleGetLocation();
}, []);

最新更新