reactjs - 将 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 },
};
};
谢谢!
解决方案
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.
推荐阅读
- r - 如何按 R 中数据框中每列的每个因子级别查找行数?
- c# - 对“Freezable”类型的引用声称它在“WindowsBase”中定义,但找不到
- python-3.x - 在 Docker Alpine Python 中安装 gevent 时出错
- javascript - 在 PHP 字符串中查找字符
- elixir - 从另一个目录导入模块
- mongodb - 无法读取未定义的属性“总计”
- integer - 朴素贝叶斯和多类分类器返回整数。数据团队说他们应该是概率
- c# - 在不同命名空间中调用相同对象的模式
- android - 确保首先调用 FirebaseApp.initializeApp(Context)。错误未向 Firebase 发送消息并且应用程序终止
- facebook-marketing-api - Facebook Marketing API 资产访问突然被拒绝