
- ReactJS 教程
- ReactJS - 首頁
- ReactJS - 簡介
- ReactJS - 路線圖
- ReactJS - 安裝
- ReactJS - 功能特性
- ReactJS - 優勢與劣勢
- ReactJS - 架構
- ReactJS - 建立 React 應用
- ReactJS - JSX
- ReactJS - 元件
- ReactJS - 巢狀元件
- ReactJS - 使用新建立的元件
- ReactJS - 元件集合
- ReactJS - 樣式
- ReactJS - 屬性 (props)
- ReactJS - 使用屬性建立元件
- ReactJS - props 驗證
- ReactJS - 建構函式
- ReactJS - 元件生命週期
- ReactJS - 事件管理
- ReactJS - 建立一個事件感知元件
- ReactJS - 在 Expense Manager 應用中引入事件
- ReactJS - 狀態管理
- ReactJS - 狀態管理 API
- ReactJS - 無狀態元件
- ReactJS - 使用 React Hooks 進行狀態管理
- ReactJS - 使用 React Hooks 的元件生命週期
- ReactJS - 佈局元件
- ReactJS - 分頁
- ReactJS - Material UI
- ReactJS - Http 客戶端程式設計
- ReactJS - 表單程式設計
- ReactJS - 受控元件
- ReactJS - 非受控元件
- ReactJS - Formik
- ReactJS - 條件渲染
- ReactJS - 列表
- ReactJS - Keys
- ReactJS - 路由
- ReactJS - Redux
- ReactJS - 動畫
- ReactJS - Bootstrap
- ReactJS - Map
- ReactJS - 表格
- ReactJS - 使用 Flux 管理狀態
- ReactJS - 測試
- ReactJS - CLI 命令
- ReactJS - 構建和部署
- ReactJS - 示例
- Hooks
- ReactJS - Hooks 簡介
- ReactJS - 使用 useState
- ReactJS - 使用 useEffect
- ReactJS - 使用 useContext
- ReactJS - 使用 useRef
- ReactJS - 使用 useReducer
- ReactJS - 使用 useCallback
- ReactJS - 使用 useMemo
- ReactJS - 自定義 Hooks
- ReactJS 高階
- ReactJS - 可訪問性
- ReactJS - 程式碼分割
- ReactJS - Context
- ReactJS - 錯誤邊界
- ReactJS - 轉發 Refs
- ReactJS - Fragments
- ReactJS - 高階元件
- ReactJS - 與其他庫整合
- ReactJS - 效能最佳化
- ReactJS - Profiler API
- ReactJS - Portals
- ReactJS - 無 ES6 ECMAScript 的 React
- ReactJS - 無 JSX 的 React
- ReactJS - 調和
- ReactJS - Refs 和 DOM
- ReactJS - Render Props
- ReactJS - 靜態型別檢查
- ReactJS - Strict Mode
- ReactJS - Web Components
- 其他概念
- ReactJS - 日期選擇器
- ReactJS - Helmet
- ReactJS - 內聯樣式
- ReactJS - PropTypes
- ReactJS - BrowserRouter
- ReactJS - DOM
- ReactJS - 走馬燈
- ReactJS - 圖示
- ReactJS - 表單元件
- ReactJS - 參考 API
- ReactJS 有用資源
- ReactJS - 快速指南
- ReactJS - 有用資源
- ReactJS - 討論
ReactJS - cache() 函式
在 React 18 中,有一個名為“cache 函式”的新特性。此函式會記住當傳遞特定輸入時發生的情況。因此,如果我們在 React 中處理某些內容時使用相同的函式和相同的引數,它不會重複執行任務。相反,它將快速返回記住的結果,從而節省使用者的時間和資源。這類似於我們的計算機記住某些內容以便更高效地執行操作。
語法
const cachedFunc = cache(func);
引數
func − func 是一個可以執行某些任務的函式,它可以使用我們提供的任何型別的資訊。
返回值
當我們使用此快取版本的函式和特定輸入時,它會檢查是否已為這些輸入儲存了結果。如果已儲存,則會直接返回結果,而無需再次執行函式。但如果沒有儲存結果,則會使用這些輸入執行原始函式,將結果儲存在其記憶體中,然後返回該結果。因此,原始函式僅在快取中沒有儲存結果時才執行。
示例
示例
以下是如何在 React 18 中使用 cache 函式的示例。在此示例中,我們將建立一個簡單的快取來計算數字的平方。
import { cache } from 'react'; // Calculate the square of a number and cache the result export const square = cache(async (num) => { console.log(`Calculating the square of ${num}`); return num * num; }); const result1 = await square(5); // Calculate and cache the result const result2 = await square(5); // Return the memoized (cached) result console.log(result1); // Calculating the square of 5, 25 console.log(result2); // 25 (No recalculation, just returns the cached result) // Use the square function const result3 = await square(3); // This will calculate and cache the result. console.log(result3); // Output: Square of 3, 9
在此示例中,我們建立了一個 square 函式,該函式計算並快取數字的平方。當我們在相同的渲染過程中使用相同的輸入(例如,5)呼叫它時,它會返回快取的結果,從而減少了重新計算的需要。當我們再次使用不同的輸入(例如,3)呼叫它時,它會計算並快取一個新的結果。
示例 - 使用 cache 避免重複工作
這是另一個顯示在 React 中使用 cache 函式的示例:
cache 函式用於儲存名為 calculateProductStats 函式的結果。cache 建立的 getProductStats 方法用於收集各種商品的統計資料。
ProductDetails 元件使用 GetProductStats 獲取單個產品的的資料,而 SalesDetails 元件使用它來獲取報表中多個商品的資料。這展示了我們如何根據需要將記憶化應用於各種方法和元件。
import { cache } from 'react'; import calculateProductStats from 'lib/product'; const getProductStats = cache(calculateProductStats); function ProductDetails({product}) { const stats = getProductStats(product); // write code here } function SalesDetails({products}) { for (let product in products) { const stats = getProductStats(product); // write code here } // write code here }
如果 ProductDetails 和 SalesReport 中都顯示了相同的 product 物件,則這兩個元件可以共享工作,並且只需為該產品呼叫一次 calculateProductStats。
假設 ProductDetails 是第一個被渲染的。它將呼叫 getProductStats 並檢視是否存在快取結果。由於這是第一次使用該產品呼叫 getProductStats,因此將發生快取未命中。然後,getProductStats 將使用該產品呼叫 calculateProductStats 並將結果儲存到快取中。
當 SalesReport 生成其產品列表併到達相同的 product 物件時,它將呼叫 getProductStats 並從快取中讀取結果。
示例 - 預載入資料
假設我們正在建立一個網頁,並且需要從資料庫中獲取一些資料以在網頁上顯示。此資料提取可能需要一些時間。我們可以使用新的 cache 函式,甚至在我們不需要資料之前就開始在後臺獲取資料。
這是一個示例:
假設我們有一個 getUser 函式,該函式從資料庫中收集使用者的 資料。即使在我們不需要使用者資料之前,我們也可以透過在 Page 元件中執行 getUser(id) 來開始獲取它。在資料檢索發生的同時,我們可以在元件中執行其他操作。
然後透過在 Profile 元件中再次呼叫 getUser 來獲取使用者資訊。如果 Page 元件的初始呼叫已經獲取並快取了使用者資料,則 Profile 元件可以使用該快取資料,而不是執行另一次緩慢的資料庫訪問。這會加快頁面速度,因為它最大限度地減少了獲取資料的等待時間。
import { cache } from 'react'; import fetchProductDetails from 'api/products'; const getProductDetails = cache(async (productId) => { return await fetchProductDetails(productId); }); function ProductInfo({ productId }) { // Fetch product details getProductDetails(productId); return ( <div> <h2>Product Information</h2> {getProductDetails(productId).description} </div> ); }
在此示例中,我們有一個 ProductInfo 元件,它使用 cache 函式開始在後臺接收產品詳細資訊。這樣,當我們需要資料時,它已經在快取中,從而減少了在頁面上顯示產品資訊所需的時間。
侷限性
在處理 React 中的伺服器請求時,每次進行新的伺服器請求時,都會清除所有記憶化函式的快取結果(快取)的記憶體儲存。
每次我們使用 cache 函式時,都會建立一個新的、不同的函式。因此,如果我們多次使用相同的原始函式呼叫 cache,我們會收到單獨的記憶化函式,並且這些記憶化函式不共享相同的儲存結果的記憶體儲存。
錯誤也會被 cache 提供的記憶化函式記住。如果原始函式為任何輸入返回錯誤,則該錯誤將儲存在記憶體中。結果,使用相同的輸入使用記憶化函式將導致相同的錯誤,而無需重新執行該函式。
重要的是,cache 方法僅用於 React 中稱為“伺服器元件”的部分。它並非用於應用程式的其他部分。
總結
“cache 函式”是 React 18 中新增的一個新特性,它允許開發人員根據宣告的輸入輕鬆儲存和檢索函式的結果。這可以節省重複計算並透過快速返回快取的結果來提高效率,從而節省重複計算,提高效率。