import { useCallback, useEffect, useState } from "react";
const [isLoading, setIsLoading] = useState(false);
const [videos, setVideos] = useState([]);
const [token, setToken] = useState(null);
useEffect(() => {
getVideos();
}, []);
const getVideos = async () => {
try {
const url = nextToken
? API_URL+ "&token=" + token
: API_URL;
console.log("Fetching data from:", url);
const data = await fetch(url);
if (!data.ok) {
throw new Error("Failed to fetch data");
}
const json = await data.json();
console.log("Response:", json);
setNextToken(json.nextPageToken);
console.log(nextToken);
setVideos((prevVideos) => [...prevVideos, ...json.items]);
} catch (error) {
console.error("Error fetching data:", error);
} finally {
setIsLoading(false);
}
在上面的代码中,尽管在 json.nextPageToken 中获得成功响应,但 nextToken 始终为 null
useState
set 方法是异步执行的,因此在更改状态后立即执行的console.log
永远不会输出新状态。相反,您可以将函数传递给 useState
set 方法,该方法在设置之前记录新状态。
所以而不是
setNextToken(json.nextPageToken);
console.log(nextToken);
那就是
setNextToken(() => {
console.log(json.nextPageToken);
return json.nextPageToken);
});