反应,状态在调用相关的setState时没有得到更新

React, state not getting updated when calling the related setState

我正在尝试从 Unsplash API 中获取图像,然后尝试使用以下代码中的 useState 更新图像数据。

const [images, setImages] = useState([]);

  useEffect(() => {
    Axios.get(
      "https://api.unsplash.com/photos/?client_id=l2U-D_PXXujBJoRiCCMCL2ifi_5ZJcK4AC0WH-A2lKk"
    )
      .then((res) => {
        //res.data is printing correct/expected value
        console.log(res.data);

        setImages(res.data);
        console.log("lul");

        //but images array is still empty
        console.log("images: ", [images]); // []
      })
      .catch((err) => console.error(err));
  }, []);

如果我将图像数组放在依赖项数组中,那么我就可以更新图像数组,但随后会无限地进行提取。

为什么会这样?

你做错的是你试图在 React re-rendered 之前 console.log。通过相关的 setState 更新 state 不是即时的,它是一个异步任务。需要 re-render 才能获得更新后的值。看下面的代码,我加了注释。

Also it's a bad idea to put images in the dependencies' array, you will get an infinite loop.

const [images, setImages] = useState([]);
 
console.log("images: ", [images]); // you get [] for the first time, and after state change and re-render, it will contains the fetched data.

useEffect(() => {
  Axios.get(
    "https://api.unsplash.com/photos/?client_id=l2U-D_PXXujBJoRiCCMCL2ifi_5ZJcK4AC0WH-A2lKk"
    )
    .then((res) => {
      setImages(res.data);
    })
    .catch((err) => console.error(err));
}, []);

setState 被异步调用(尽管 return 不是一个承诺,所以你不能 await 它)。

保持你的 useEffect 不变,为了在 images 改变时打印新值,你可以使用另一个 useEffect:

  useEffect(() => {
    console.log("images: ", [images]); // []
  }, [images]);