next.js路由器更改url,但仍然呈现相同的页面.并且不导航到另一个页面

mrphzbgm  于 2023-02-12  发布在  其他
关注(0)|答案(1)|浏览(384)

我有一个显示搜索结果的路径/discovery,我还尝试将搜索状态与url查询参数同步,因此如果用户键入“chicken”,url将变为-/discovery?query=chicken&page=1
用户点击结果后,将导航至/mealpreview/[id]
然而,当我尝试像这样往回导航时:

<IconButton color="inherit" onClick={() => router.back()}>
        <ArrowBackIcon />
      </IconButton>

URL变回-/discovery?query=chicken&page=1,但是它仍然呈现相同的页面。
当我再次点击返回按钮时,它工作并返回到/discovery
当我不使用url参数时一切正常,这里发生了什么?
顺便说一下,这是我如何同步我的网址状态:

import React, { Component } from "react";
import qs from "qs";

const updateAfter = 700;
export const isClient = !(typeof window === "undefined");

const searchStateToURL = (searchState) =>
  searchState ? `${window.location.pathname}?${qs.stringify(searchState)}` : "";

const withURLSync = (TestSearch) =>
  class WithURLSync extends Component {
    state = {
      searchState: qs.parse(isClient && window.location.search.slice(1)),
    };

    componentDidMount() {
      if (isClient) {
        window.addEventListener("popstate", this.onPopState);
      }
    }

    componentWillUnmount() {
      clearTimeout(this.debouncedSetState);
      window.removeEventListener("popstate", this.onPopState);
    }

    onPopState = ({ state }) =>
      this.setState({
        searchState: state || {},
      });

    onSearchStateChange = (searchState) => {
      clearTimeout(this.debouncedSetState);

      this.debouncedSetState = setTimeout(() => {
        window.history.pushState(
          searchState,
          null,
          searchStateToURL(searchState)
        );
      }, updateAfter);

      this.setState({ searchState });
    };

    render() {
      const { searchState } = this.state;

      return (
        <TestSearch
          {...this.props}
          searchState={searchState}
          onSearchStateChange={this.onSearchStateChange}
          createURL={searchStateToURL}
        />
      );
    }
  };

export default withURLSync;
6yt4nkrj

6yt4nkrj1#

请使用NextJs router.pushrouter.replace,而不要使用window.history.pushState

相关问题