您好,登錄后才能下訂單哦!
React中如何獲取數(shù)據(jù),針對(duì)這個(gè)問(wèn)題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問(wèn)題的小伙伴找到更簡(jiǎn)單易行的方法。
1、使用生命周期方法請(qǐng)求數(shù)據(jù)
應(yīng)用程序Employees.org做兩件事:
(1).一進(jìn)入程序就獲取20名員工。
(2).可以通過(guò)過(guò)濾條件來(lái)篩選員工。
在實(shí)現(xiàn)這兩個(gè)需求之前,先來(lái)回顧一下React 類(lèi)組件的2個(gè)生命周期方法:
鴻蒙官方戰(zhàn)略合作共建——HarmonyOS技術(shù)社區(qū)
componentDidMount():組件掛載后執(zhí)行
componentDidUpdate(prevProps):當(dāng) props 或 state 改變時(shí)執(zhí)行
組件 <EmployeesPage>使用上面兩個(gè)生命周期方法實(shí)現(xiàn)獲取邏輯:
import EmployeesList from "./EmployeesList"; import { fetchEmployees } from "./fake-fetch"; class EmployeesPage extends Component { constructor(props) { super(props); this.state = { employees: [], isFetching: true }; } componentDidMount() { this.fetch(); } componentDidUpdate(prevProps) { if (prevProps.query !== this.props.query) { this.fetch(); } } async fetch() { this.setState({ isFetching: true }); const employees = await fetchEmployees(this.props.query); this.setState({ employees, isFetching: false }); } render() { const { isFetching, employees } = this.state; if (isFetching) { return <div>獲取員工數(shù)據(jù)中...</div>; } return <EmployeesList employees={employees} />; } }
打開(kāi)codesandbox可以查看 <EmployeesPage>獲取過(guò)程。
<EmployeesPage>有一個(gè)獲取數(shù)據(jù)的異步方法fetch()。在獲取請(qǐng)求完成后,使用 setState 方法來(lái)更新employees。
this.fetch()在componentDidMount()生命周期方法中執(zhí)行:它在組件初始渲染時(shí)獲取員工數(shù)據(jù)。
當(dāng)咱們關(guān)鍵字進(jìn)行過(guò)濾時(shí),將更新 props.query 。每當(dāng) props.query 更新,componentDidUpdate()就會(huì)重新執(zhí)行this.fetch()。
雖然生命周期方法相對(duì)容易掌握,但是基于類(lèi)的方法存在樣板代碼使重用性變得困難。
優(yōu)點(diǎn)
這種方法很容易理解:componentDidMount()在第一次渲染時(shí)獲取數(shù)據(jù),而componentDidUpdate()在props更新時(shí)重新獲取數(shù)據(jù)。
缺點(diǎn)
樣板代碼
基于類(lèi)的組件需要繼承React.Component,在構(gòu)造函數(shù)中執(zhí)行 super(props) 等等。
this
使用 this 關(guān)鍵字很麻煩。
代碼重復(fù)
componentDidMount()和componentDidUpdate()中的代碼大部分是重復(fù)的。
很難重用
員工獲取邏輯很難在另一個(gè)組件中重用。
2、使用 Hooks 獲取數(shù)據(jù)
Hooks 是基于類(lèi)獲取數(shù)據(jù)方式更好的選擇。作為簡(jiǎn)單的函數(shù),Hooks 不像類(lèi)組件那樣還要繼承,并且也更容易重用。
簡(jiǎn)單回憶一下useEffect(callback[, deps]) Hook 。這個(gè)hook在掛載后執(zhí)行callback ,并且當(dāng)依賴項(xiàng)deps發(fā)生變化時(shí)重新渲染。
如下示例所示,在<EmployeesPage>中使用useEffect()獲取員工數(shù)據(jù):
import EmployeesList from "./EmployeesList"; import { fetchEmployees } from "./fake-fetch"; function EmployeesPage({ query }) { const [isFetching, setFetching] = useState(false); const [employees, setEmployees] = useState([]); useEffect(function fetch() { (async function() { setFetching(true); setEmployees(await fetchEmployees(query)); setFetching(false); })(); }, [query]); if (isFetching) { return <div>Fetching employees....</div>; } return <EmployeesList employees={employees} />; }
打開(kāi)codesandbox可以查看useEffect()如何獲取數(shù)據(jù)。
可以看到使用 Hooks 的 <EmployeesPage>比使用類(lèi)組件方式簡(jiǎn)單了很多。
在<EmployeesPage>函數(shù)組件中的useEffect(fetch, [query]),初始渲染之后執(zhí)行fetch回調(diào)。此外,當(dāng)依賴項(xiàng) query 更新時(shí)也會(huì)重新執(zhí)行 fetch 方法。
但仍有優(yōu)化的空間。Hooks 允許咱們從<EmployeesPage>組件中提取雇員獲取邏輯,來(lái)看看:
import React, { useState } from 'react'; import EmployeesList from "./EmployeesList"; import { fetchEmployees } from "./fake-fetch"; function useEmployeesFetch(query) { // 這行有變化 const [isFetching, setFetching] = useState(false); const [employees, setEmployees] = useState([]); useEffect(function fetch { (async function() { setFetching(true); setEmployees(await fetchEmployees(query)); setFetching(false); })(); }, [query]); return [isFetching, employees]; } function EmployeesPage({ query }) { const [employees, isFetching] = useEmployeesFetch(query); // 這行有變化 if (isFetching) { return <div>Fetching employees....</div>; } return <EmployeesList employees={employees} />; }
從useEmployeesFetch()提到所需要的值。組件<EmployeesPage>沒(méi)有相應(yīng)的獲取邏輯,只負(fù)責(zé)渲染界面工作。
更好的是,可以在需要獲取雇員的任何其他組件中重用useEmployeesFetch()。
優(yōu)點(diǎn)
清楚和簡(jiǎn)單
Hooks沒(méi)有樣板代碼,因?yàn)樗鼈兪瞧胀ǖ暮瘮?shù)。
可重用性
在 Hooks 中實(shí)現(xiàn)的獲取數(shù)據(jù)邏輯很容易重用。
缺點(diǎn)
需要前置知識(shí)
Hooks 有點(diǎn)違反直覺(jué),因此在使用之前必須理解它們,Hooks 依賴于閉包,所以一定要很好地了解它們。
必要性
使用Hooks,仍然必須使用命令式方法來(lái)執(zhí)行數(shù)據(jù)獲取。
3、使用 suspense 獲取數(shù)據(jù)
Suspense 提供了一種聲明性方法來(lái)異步獲取React中的數(shù)據(jù)。
注意:截至2019年11月,Suspense 處于試驗(yàn)階段。
<Suspense>包裝執(zhí)行異步操作的組件:
<Suspense fallback={<span>Fetch in progress...</span>}> <FetchSomething /> </Suspense>
數(shù)據(jù)獲取時(shí),Suspense將顯示fallback中的內(nèi)容,當(dāng)獲取完數(shù)據(jù)后,Suspense將使用獲取到數(shù)據(jù)渲染<FetchSomething />。
來(lái)看看怎么使用Suspense:
import React, { Suspense } from "react"; import EmployeesList from "./EmployeesList"; function EmployeesPage({ resource }) { return ( <Suspense fallback={<h2>Fetching employees....</h2>}> <EmployeesFetch resource={resource} /> </Suspense> ); } function EmployeesFetch({ resource }) { const employees = resource.employees.read(); return <EmployeesList employees={employees} />; }
打開(kāi)codesandbox可以查看Suspense如何獲取數(shù)據(jù)。
<EmployeesPage>使用Suspense處理組件將獲取到數(shù)據(jù)傳遞給<EmployeesFetch>組件。
<EmployeesFetch>中的resource.employees是一個(gè)特殊包裝的promise,它在背后與Suspense進(jìn)行通信。這樣,Suspense就知道“掛起” <EmployeesFetch>的渲染要花多長(zhǎng)時(shí)間,并且當(dāng)資源準(zhǔn)備就緒時(shí),就開(kāi)始執(zhí)行渲染工作。
最大的優(yōu)點(diǎn)是:Suspense 以聲明性和同步的方式處理異步操作。組件沒(méi)有復(fù)雜數(shù)據(jù)獲取邏輯,而是以聲明方式使用資源來(lái)渲染內(nèi)容。在組件內(nèi)部沒(méi)有生命周期,沒(méi)有 Hooks,async/await,沒(méi)有回調(diào):僅展示界面。
優(yōu)點(diǎn)
聲明式
Suspense 以聲明的方式在React中執(zhí)行異步操作。
簡(jiǎn)單
聲明性代碼使用起來(lái)很簡(jiǎn)單,這些組件沒(méi)有復(fù)雜的數(shù)據(jù)獲取邏輯。
松耦合與獲取實(shí)現(xiàn)
使用Suspense的組件看不出如何獲取數(shù)據(jù):使用 REST 或 GraphQL。Suspense設(shè)置一個(gè)邊界,保護(hù)獲取細(xì)節(jié)泄露到組件中。
關(guān)于React中如何獲取數(shù)據(jù)問(wèn)題的解答就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,如果你還有很多疑惑沒(méi)有解開(kāi),可以關(guān)注億速云行業(yè)資訊頻道了解更多相關(guān)知識(shí)。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。