为什么我的 axios 请求在控制台中打印但没有设置状态
我试图在 React 组件中显示数据库中的一些数据,但数据没有保存在状态挂钩中,但请求的响应确实在控制台中打印。
我该如何解决这个问题?
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [collections, setCollections] = useState([]);
useEffect(() => {
const getCollections = async () => {
try {
const response = await axios.get('http://localhost:4000/api/collections');
setIsLoaded(true);
console.log(response); // This prints the response
setCollections(response);
console.log(collections); // This prints []
} catch (error) {
setError(error);
setIsLoaded(true);
}
}
getCollections();
}, [])
I'm trying to display some data from my database in my React component but the data isn't getting saved in the state hook, but the request's response does print in the console.
How can I fix this?
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [collections, setCollections] = useState([]);
useEffect(() => {
const getCollections = async () => {
try {
const response = await axios.get('http://localhost:4000/api/collections');
setIsLoaded(true);
console.log(response); // This prints the response
setCollections(response);
console.log(collections); // This prints []
} catch (error) {
setError(error);
setIsLoaded(true);
}
}
getCollections();
}, [])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
setCollections
不会立即被 React 执行。新状态应该在下一次渲染时可用。尝试在渲染阶段记录日志:setCollections
is not executed immediately by React. The new state should be available on the next render. Try logging during the render phase: