成功获取请求后,React useState 变量未更新

问题描述 投票:0回答:1
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

reactjs fetch state
1个回答
0
投票

useState
set 方法是异步执行的,因此在更改状态后立即执行的
console.log
永远不会输出新状态。相反,您可以将函数传递给
useState
set 方法,该方法在设置之前记录新状态。 所以而不是

setNextToken(json.nextPageToken);
console.log(nextToken);

那就是

setNextToken(() => {
    console.log(json.nextPageToken);
    return json.nextPageToken);
});
© www.soinside.com 2019 - 2024. All rights reserved.