【问题标题】:React, state not getting updated when calling the related setStateReact,调用相关的setState时状态未更新
【发布时间】:2022-08-14 00:18:44
【问题描述】:
我正在尝试从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));
}, []);
如果我将图像数组放在依赖数组中,那么我可以更新图像数组,但随后会无限地进行获取。
为什么会这样?
标签:
javascript
reactjs
use-effect
use-state
【解决方案1】:
您做错了什么是您在 React 重新渲染之前尝试console.log。通过相关的setState 更新state 不是即时的,它是一个异步任务。记录状态更改的一种方法是在定义 console.log 之后添加它:
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));
}, []); // It's a bad idea to put `images` in the dependencies' array, you will get an infinite loop.
【解决方案2】:
setState 被异步调用(虽然它不返回承诺,所以你不能 await 它)。
保持您的useEffect 不变,并且为了在images 更改时打印新值,您可以使用另一个useEffect:
useEffect(() => {
console.log("images: ", [images]); // []
}, [images]);