首页 > 解决方案 > 如何在 nextjs 中获取上一个 url

问题描述

如何在 nextjs 中获取上一个 URL?我认为这些价值观是不同this.props.router.asPathnextProps.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 来移动页面?

标签: next.js

解决方案


您可以在getServerSideProps或任何其他数据获取方法的上下文中找到引用者(即之前的 URL)

作为

    context.req.headers.referer  

代码中的示例

    export async function getServerSideProps(context) {
      console.log(context.req.headers.referer)
    }

推荐阅读