我試圖在我的 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();
}, [])
控制臺日志
uj5u.com熱心網友回復:
setCollectionsReact 不會立即執行。新狀態應該在下一次渲染時可用。在渲染階段嘗試記錄:
const [error, setError] = useState(null);
const [isLoaded, setIsLoaded] = useState(false);
const [collections, setCollections] = useState([]);
console.log(collections);
useEffect(() => {
...
}, [])
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/435192.html
標籤:javascript 反应 api axios
