shfshanyue / Daily-Question

互联网大厂内推及大厂面经整理,并且每天一道面试题推送。每天五分钟,半年大厂中
https://q.shanyue.tech
4.95k stars 510 forks source link

【Q066】如何使用 react hooks 实现 useFetch 请求数据 #67

Open shfshanyue opened 4 years ago

shfshanyue commented 4 years ago

比如设计成 useFetch 这种形式,它的 API 应该如何设计

shfshanyue commented 4 years ago

可以参考 How to fetch data with React Hooks?

zfy171 commented 2 years ago

import React, { Fragment, useState, useEffect } from "react";

function App() { const [data, setData] = useState([]); useEffect(() => { async function fetchData() { // You can await here const response = await MyAPI.getData(someId); setData(response); } fetchData(); }, []); return (

); }

export default App;