尝试使用fetch和promise来获取数据是行不通的(react)



我试图用fetch从API中获取数据,我可以在fetch中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

但是CCD_ 2一直在说";未定义";。

有人能帮帮我吗?

在记录异步操作之前,您必须等待异步操作完成。

let data = fetchData(URL).then(() => {console.log(data);});

(也可以删除then(result => console.log(result))或从中返回结果)

fetchData是一个async函数,这就是为什么在解析fetchData之前执行console.log的原因:

export const fetchData = async (url) => {  
return fetch(url)
.then(response => response.json())
.then(result => (result)) //--> data
.catch(error => console.log('error', error))
}

然后在组件中,内部使用效果:

function App() {
const [data, setData] = useState([]) //--> keep data in component state

useEffect(()=> {
fetchData(URL) //--> fetch data when component is mounted
.then(response => setData(response))
}, []);
//...
}

最新更新