Как получить URL предыдущей страницы в nextjs - PullRequest
0 голосов
/ 28 мая 2020

Я создал файл _app. js и добавил в него этот код, который должен сохранять состояние предыдущего URL-адреса в массиве. При попытке получить доступ к предыдущему URL-адресу я просто получаю текущий URL-адрес страницы.

Что-то не так в logi c кода _app. js или при передаче значения history другим компонентам / pages?

_app. js

import React from 'react';
import App from 'next/app';

class MyApp extends App {
  static async getInitialProps({ Component, ctx }) {
    let pageProps = {};

    if (Component.getInitialProps) {
      pageProps = await Component.getInitialProps(ctx);
    }

    return { pageProps };
  }

  state = {
    history: []
  };

  componentDidMount() {
    const { asPath } = this.props.router;

    this.setState(prevState => ({ history: [...prevState.history, asPath] }));

  }

  componentDidUpdate() {
    const { history } = this.state;
    const { asPath } = this.props.router;

    if (history[history.length - 1] !== asPath) {
      this.setState(prevState => ({ history: [...prevState.history, asPath] }));
    }
  }



  render() {
    const { Component, pageProps } = this.props
    return <Component history={this.state.history} {...pageProps} />
  }
}

export default MyApp;

Пример передачи истории

const CatPage = ({ history }) => {
  console.log(history) //I get the value of a current page 
  console.log(history[0]) // same thing it is just the current url in the array
}
...