我正在尝试使用 fetch 从 API 中获取数据,我可以
console.log
获取结果,但在 fetch 之外我无法获取数据。
所以我得到了这个 fetchData.js 文件,其中包含该函数:
export const fetchData = (url) => {
return fetch(url)
.then(response => response.json())
.then(result => console.log(result))
.catch(error => console.log('error', error))
}
然后在 app.jsx 文件中我这样调用该函数:
import { fetchData } from "./fetchData";
const URL = "https://pokeapi.co/api/v2/pokemon"
function App() {
let data = fetchData(URL);
console.log(data);
//return etc
但是
console.log(data)
一直说“未定义”。
有人可以帮助我吗?
您必须等待异步操作完成才能记录它。
let data = fetchData(URL).then(() => {console.log(data);});
(也可以删除
then(result => console.log(result))
或从中返回结果)
fetchData
是一个 async
函数,这就是为什么 console.log 在 fetchData 解析之前执行:
export const fetchData = async (url) => {
return fetch(url)
.then(response => response.json())
.then(result => (result)) //--> data
.catch(error => console.log('error', error))
}
然后在组件中,useEffect里面:
function App() {
const [data, setData] = useState([]) //--> keep data in component state
useEffect(()=> {
fetchData(URL) //--> fetch data when component is mounted
.then(response => setData(response))
}, []);
//...
}