首页 > 解决方案 > 将 Nextjs 的 getServerSideProps 中获取的数据持久保存到应用程序的其余部分,而无需在页面加载时重新获取

问题描述

我有一个索引页,其中包括在getServerSideProps.

如果我使用next/link或者可能router.push()- 有没有办法让这些数据持续到我的应用程序中的其余页面?

或者这是我需要使用 Context/Redux 之类的场景?

例如:

索引.tsx

const App = ({ productData }: IndexProps) => {
  return (
    <Link href={`/product/${title}`}> ... </Link>
  )
}

export const getServerSideProps: GetServerSideProps = async () => {
  const productData = await getProducts();

  return {
    props: { productData },
  };
};

/product/[id].tsx

const Product = ({ productData }) => {
  return (
    <Link href={`/product/${title}`}> ... </Link>
  )
}

export const getServerSideProps: GetServerSideProps = async () => {

  if (PRODUCTDATADOESNTEXIST) {
    const productData = await getProducts();
  }
  
// else use data fetched in from previous page?

  return {
    props: { productData },
  };
};

谢谢!

标签: reactjsreduxnext.jsreact-state-management

解决方案


You can create a service that will cache the data in memory.

Something like this.

const cache = {};

export const setProducts = (products) => {
    products.forEach((p) => {
        cache[p.id] = p;
    });
};


const getProduct = (id) {

    if(cache[id]){
        Promise.resolve(cache[id]);
        
    }
    // make the API call to fetch data; 

}

export default getProduct;

Use the set method to store the data from the NextJS Page and use the get method to fetch data when needed.


推荐阅读