通过 useRef 实现数据缓存

通过 useRef 可以实现数据的缓存。useRef 返回一个可变的 ref 对象,可以在组件的整个生命周期中保持稳定的引用。

下面是使用 useRef 来实现数据缓存的示例代码:

import React, { useEffect, useRef } from 'react';

function MyComponent() {
  const cachedData = useRef(null);

  useEffect(() => {
    // 判断缓存中是否存在数据
    if (cachedData.current === null) {
      // 从 API 获取数据
      fetch('https://api.example.com/data')
        .then(response => response.json())
        .then(data => {
          // 将数据保存到缓存
          cachedData.current = data;
          console.log('Data fetched from API:', data);
        })
        .catch(error => {
          console.error('Error fetching data:', error);
        });
    } else {
      // 使用缓存中的数据
      console.log('Data from cache:', cachedData.current);
    }
  }, []);

  return (
    // 组件的 JSX
  );
}

.

posted @ 2022-08-14 23:56  每天都要进步一点点  阅读(297)  评论(0)    收藏  举报