📜  如何在 ReactJS 中获取单个缓存数据?

📅  最后修改于: 2022-05-13 01:56:51.879000             🧑  作者: Mango

如何在 ReactJS 中获取单个缓存数据?

我们可以在 ReactJS 中使用以下方法来获取单个缓存数据。我们可以从浏览器获取单个缓存数据,并在需要时在我们的应用程序中使用它。缓存是一种技术可以帮助我们将给定资源的副本存储到浏览器中,并在请求时将其返回。

方法:按顺序执行这些简单的步骤 在 ReactJS 中获取单个缓存数据。我们创建了getSingleCacheData函数,该函数获取缓存名称并从浏览器缓存中获取其数据。当我们点击按钮时,该函数被触发并从缓存中获取数据。在以下示例中,我们尝试从浏览器中获取名为 CacheOne 的单个缓存数据,该浏览器具有五个缓存,分别名为 CacheOne、CacheTwo、CacheThree、CacheFour 和 CacheFive,如下所示:

创建反应应用程序:

  • 第 1 步:使用以下命令创建一个 React 应用程序:

    npx create-react-app foldername
  • 第 2 步:创建项目文件夹(即文件夹名称)后使用以下命令移动到该文件夹:

    cd foldername

项目结构:它将如下所示。

项目结构

App.js:现在在App.js文件中写下以下代码。在这里,App 是我们编写代码的默认组件。

Javascript
import * as React from 'react';
  
export default function App() {
  
  // Our state to store fetched cache data
  const [cacheData, setCacheData] = React.useState();
  
  // Function to get single cache data
  const getSingleCacheData = async (cacheName, url) => {
    if (typeof caches === 'undefined') return false;
    
    const cacheStorage = await caches.open(cacheName);
    const cachedResponse = await cacheStorage.match(url);
    
    // If no cache exists
    if (!cachedResponse || !cachedResponse.ok) {
      setCacheData('Fetched failed!')
    }
  
    return cachedResponse.json().then((item) => {
      setCacheData(item)
    });
  };
  
  // Cache Object 
  const cacheToFetch = { cacheName: 'CacheOne', url: 'https://localhost:300' }
  
  return (
    
      

How to get single cache data in ReactJS?

       
        
Cache Data is: {cacheData}
    
  ); }


运行应用程序的步骤:从项目的根目录使用以下命令运行应用程序:

npm start

输出:现在打开浏览器并转到http://localhost:3000/ ,您将看到以下输出: