现有线程大多与页面路由器相关。
我知道使用 React Router 我可以做到这一点:
const history = useHistory();
const { pathname } = useLocation();
history.push('/', { from: pathname })
然后像这样访问之前的路径:
const Home = (props) => {
console.log(props.location.state.from);
}
但是如何使用 App Router 在 NextJS 14 中实现这一目标?
我尝试访问
asPath
道具,但显然它已被删除:
const usePreviousRoute = () => {
const { asPath } = useRouter();
const ref = useRef<string | null>(null);
useEffect(() => {
ref.current = asPath;
}, [asPath]);
return ref.current;
};
如果您被允许在页面上使用 getServerSideProps(ctx) 或其他获取方法,您需要有关上一页的信息,然后可以从上下文中获取它。
ctx.req.headers.referer