当多个页面共享相同的数据源时,如何设计统一的数据获取逻辑?

解读

该问题考察Next.js开发者对数据共享和复用能力的理解,重点在于如何避免重复代码、提升性能以及维护数据一致性。在企业级开发中,多个页面可能需要访问同一后端API或数据库,例如商品信息、用户配置等。面试官希望了解候选人是否能结合Next.js特性(如API路由、数据缓存、服务端渲染)设计可扩展、可维护的解决方案。

知识点

  1. Next.js数据获取机制:getStaticProps、getServerSideProps、API路由
  2. 数据共享策略:模块化、数据层抽象、缓存优化
  3. 性能考量:减少重复请求、提升渲染效率、SEO友好性
  4. 代码复用技术:自定义钩子(hooks)、服务封装、中间件

答案

在Next.js中,可通过以下方式设计统一的数据获取逻辑:

1. 创建共享数据服务层

将公共数据逻辑封装到独立模块中,例如:

// services/data.js
export async function fetchDataFromAPI(endpoint) {
  const res = await fetch(`https://api.example.com/${endpoint}`, {
    cache: 'force-cache', // 启用缓存提升性能
    next: { revalidate: 60 }, // ISR配置,每60秒刷新缓存
  });
  if (!res.ok) throw new Error('数据获取失败');
  return res.json();
}

在页面中调用:

// pages/products.js
import { fetchDataFromAPI } from '../services/data';

export async function getStaticProps() {
  const products = await fetchDataFromAPI('products');
  return { props: { products } };
}

2. 利用API路由统一数据接口

通过Next.js的API路由创建通用数据接口,例如:

// pages/api/data.js
export default async function handler(req, res) {
  const { endpoint } = req.query;
  const data = await fetchDataFromAPI(endpoint); // 调用共享服务
  res.status(200).json(data);
}

页面通过HTTP请求调用:

// pages/products.js
export async function getStaticProps() {
  const res = await fetch(`https://api.example.com/data?endpoint=products`);
  const products = await res.json();
  return { props: { products } };
}

3. 使用自定义钩子(hooks)复用逻辑

在函数组件中封装数据获取逻辑:

// utils/useFetchData.js
import { useEffect, useState } from 'react';

export function useFetchData(endpoint) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function fetchData() {
      try {
        const res = await fetch(`https://api.example.com/${endpoint}`);
        if (!res.ok) throw new Error('请求失败');
        setData(await res.json());
      } catch (err) {
        setError(err.message);
      } finally {
        setLoading(false);
      }
    }
    fetchData();
  }, [endpoint]);

  return { data, loading, error };
}

页面组件中调用:

// pages/products.js
import useFetchData from '../utils/useFetchData';

export default function Products({ products }) {
  const { data, loading } = useFetchData('products');
  if (loading) return <div>加载中...</div>;
  return <div>{data.map(product => <div key={product.id}>{product.name}</div>)}</div>;
}

4. 结合ISR实现缓存策略

通过next.config.js配置全局缓存策略:

// next.config.js
module.exports = {
  experimental: {
    incrementalStaticRegeneration: true,
  },
  async rewrites() {
    return [
      {
        source: '/api/data/:endpoint',
        destination: '/data?endpoint=:endpoint', // 重定向到API路由
      },
    ];
  },
};

拓展思考

  • 数据一致性:需确保共享数据服务与后端API版本同步,避免因接口变更导致错误。
  • 性能优化:通过cache: 'force-cache'和revalidate参数控制缓存粒度,减少服务器负载。
  • 错误处理:在数据服务层统一添加重试机制或降级策略,例如:
    // services/data.js
    async function fetchDataFromAPI(endpoint, retries = 3) {
      for (let i = 0; i < retries; i++) {
        try {
          const res = await fetch(`https://api.example.com/${endpoint}`);
          if (res.ok) return res.json();
          throw new Error('请求失败');
        } catch (err) {
          console.error(`第${i + 1}次尝试失败,重试中...`);
          await new Promise(resolve => setTimeout(resolve, 1000));
        }
      }
      throw new Error('所有尝试失败');
    }
    
  • 动态数据需求:若部分页面需要动态参数,可通过getServerSideProps结合params实现:
    // pages/products/[id].js
    export async function getServerSideProps({ params }) {
      const product = await fetchDataFromAPI(`products/${params.id}`);
      return { props: { product } };
    }
    
  • 团队协作规范:建议将共享数据服务统一放置在/services目录,并通过TypeScript定义接口类型,确保代码可维护性。