next.js - 如何在 nextjs 中获取上一个 url
问题描述
如何在 nextjs 中获取上一个 URL?我认为这些价值观是不同this.props.router.asPath
的nextProps.router.asPath
。
实际上,我想router.push
在登录后打电话。我知道router.back
转到上一页。但是可以转到另一个站点。有历史栈的用户去上一页,没有历史栈的用户去/
主页面。
import { Component } from 'react'
import App, { Container } from 'next/app';
import ErrorComponent from '@/components/error'
export default class MyApp extends App {
render() {
console.log(this.props)
const { Component, pageProps, router } = this.props;
const props = {
...pageProps,
router
}
return (
<ErrorBoundary>
<Container>
<Component {...props} />
</Container>
</ErrorBoundary>
);
}
componentWillReceiveProps(nextProps) {
// previous page url /contents
console.log(this.props.router.asPath) // /about
console.log(nextProps.router.asPath) // /about
console.log('window.history.previous.href', window.history.previous) // undefined
}
}
我该如何解决?或者我怎样才能在登录后获取以前的 URL 来移动页面?
解决方案
您可以在getServerSideProps或任何其他数据获取方法的上下文中找到引用者(即之前的 URL)
作为
context.req.headers.referer
代码中的示例
export async function getServerSideProps(context) {
console.log(context.req.headers.referer)
}
推荐阅读
- php - 代客不适用于 WordPress 网站:建立数据库连接时出错
- c++ - 用c ++中函数的返回值初始化一个类
- java - Java (Selenium) - 用于初始化子类的超类构造函数
- javascript - 无法使用 react.js 将其他文件导入 client.js
- sql - Postgres - 查询以从多个表中选择字段作为列
- python - 如何从 Python 中的内部类访问外部类成员?
- c++ - C ++如何从迭代器(内部类)访问集合成员变量-这有意义吗?
- typescript - 打字稿中抽象类的依赖注入
- imagemagick - 使用 Imagemagick PHP 将图像 75 dpi 转换为 300 dpi
- java - 在 NetBeans 中逐行读取文本文件