[英]How to reload Next.js page initial props without reloading the whole page
我有一個 Next.js 頁面,它在getInitialProps
function 中獲取數據,我想從瀏覽器重新加載這些數據而不重新加載頁面,這將是性能不佳並丟失用戶的滾動 Z4757FE07FD4982ADBEEAZ6766 有沒有辦法在不重新加載整個頁面的情況下重新加載初始道具?
這可以通過調用router.replace
來完成:
import { useRouter } from 'next/router';
function YourPage({ someProps }) {
const router = useRouter();
// Call this function when you want to refresh the data
const refreshData = () => router.replace(router.asPath);
// Your JSX
}
router.replace
是一種無需在歷史記錄中添加新條目即可更新 URL 的方法。 router.asPath
是當前的 URL。 所以這就像做一個客戶端重定向到同一個頁面,客戶端重定向重新獲取道具。
我不相信上面的答案行不通,因為函數無法序列化並從服務器發送到客戶端。
您可以使用將最后一個初始道具存儲為 state 的高階組件,並且可以通過調用getInitialProps
並將 state 設置為其返回值來重新加載它們。 這是一個可以做到這一點的 HOC:
import { NextPage, NextPageContext } from 'next';
import React, { useState, PropsWithChildren, ComponentType } from 'react';
/**
* Removes never-used context values to reduce bloat. Context values may come from server but then
* be used client-side because they are saved in initial props.
*/
function minifyContext(context) {
return { ...context, req: undefined, res: undefined };
}
const withSoftReload = Page => {
async function getInitialProps(ctx) {
return { context: minifyContext(ctx), ...(await Page.getInitialProps(ctx)) };
}
const omitContextFromProps = ({
context,
...props
}) => props;
const NewPage = props => {
// set inner page initial props to wrapper initial props minus context
const [initialProps, setInitialProps] = useState(omitContextFromProps(props));
async function softReload() {
setInitialProps({ children: null, ...(await Page.getInitialProps(props.context)) });
}
return (
<Page
{...{ ...initialProps, softReload }}
/>
);
};
NewPage.getInitialProps = getInitialProps;
NewPage.displayName = `withSoftReload(${Page.displayName})`;
return NewPage;
};
export default withSoftReload;
在您的頁面中,您會像這樣使用它:
const MyPage = ({ data, softReload }) => (
<div>
{data}
<button onClick={softReload}>Refresh</button>
</div>
);
MyPage.getInitialProps = async (ctx) => {
// fetch data
};
export default withSoftReload(MyPage);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.