jon*_*bbs 9 reactjs next.js next-router
我有一个可以搜索的网站。我希望用户能够点击搜索结果并在叠加层中打开产品,而不是重新加载整个页面,但是我希望 url 栏中的 url 是正确的产品页面,以便是用户复制并粘贴它或在新选项卡中打开它,他们将获得产品页面。我还希望后退按钮在这两种情况下都可以使用。
这是该过程的更详细说明。
起初我想我可以在 Next/Router 上使用 {shallow:true} 选项来让它工作,但文档特别说这仅适用于相同的页面导航(使用不同的查询字符串)。
我唯一的想法是,我可以将链接设置为正确的,但在浏览器中劫持它以在历史状态下用纯 javascript 做一些事情,但我不确定是否可以从等式中删除下一个路由器。
需要说明的是,我不是在寻求产品页面或覆盖层本身的帮助,我可以轻松创建在两种情况下显示相同内容的共享组件,特别是我请求帮助的路由和 URL 问题。
任何帮助,即使只是指向正确方向的指针,也将不胜感激。
我是这样做的。
您需要创建一个可选的 catch all 路由。IE:pages/search/[[searchParams]].tsx
import { useRouter } from 'next/router';
import { GetServerSidePropsContext } from 'next';
import { ProductsView, ProductDetailsView } from '@/views';
export async function getServerSideProps({
params,
}: GetServerSidePropsContext) {
const [productId = null] = (params?.searchParams as string[]) || [];
return {
props: {
productId,
},
};
}
interface Props {
productId?: string;
}
function SearchProductsPage({ productId }: Props) {
const router = useRouter();
// You could use next/link in your views instead of using next/router
const onViewDetails = (productDetailsId: string) => {
router.push(productDetailsId, `product/${productDetailsId}`).catch((e) => {
console.error(e);
});
};
// Going back to /search will remove the productId and the overlay view will be removed
const onClose = () => {
router.push('/search').catch((e) => {
console.error(e);
});
};
// If you have a productId (catch from URL and received via Props)
// it will render the Product details view which contains the overlay and the product details
return (
<>
<ProductsView onViewDetails={onViewDetails} />
{productId && <ProductDetailsView productId={productId} onClose={onClose} />}
</>
);
}
export default SearchProductsPage;
Run Code Online (Sandbox Code Playgroud)
请注意,路由到/product/${productDetailsId}
而不是product/${productDetailsId}
会给你一个错误。所以你使用这段代码,你最终会得到像这样的 URL/search/product/1
而不是/product/1
.
但是您可以创建一个单独的页面,pages/product/[productId].tsx
即呈现产品详细信息视图,而不是在叠加层中。
归档时间: |
|
查看次数: |
796 次 |
最近记录: |