【发布时间】:2022-10-05 06:01:35
【问题描述】:
我正在使用 axios 从 API(对象的 arr)中提取数据,但由于某种原因,在钩子内调用它时,我一直收到未决的承诺。
我使用承诺链来确保代码同步执行,但它仍然是相同的。
例如,当我使用“console.log(selectedVideo[0]”时,我得到“未定义”。我认为这是因为它在完成提取数据之前调用 API,对吗?
const url = `${baseURL}videos?api_key=${apiKEY}`;
const fetchData = axios
.get(url)
.then((resp) => setSelectedVideo(resp.data));
useEffect(() => {
fetchData();
}, []);
// sets the state for the video
const [selectedVideo, setSelectedVideo] = useState(fetchData);
console.log(selectedVideo);
【问题讨论】:
-
尝试把 settimeout
标签: javascript reactjs react-hooks axios