在 next js 中使用浏览器历史记录状态

Ste*_*e K 10 javascript reactjs next.js

我正在尝试使用 nextjs 实现自定义滚动。我希望能够在用户离开时保存页面的滚动位置,以便当他们使用 popstate 返回时我可以重置滚动位置。

问题是,当我尝试使用replaceState历史 api 时,next/router 会覆盖我用它们自己的数据放置的内容。Next/router 不为其路由器提供任何类型的历史记录,并且他们不放置 id 或任何我可以引用以使用我自己的状态的内容。所以我无法引用我实际所在的历史堆栈的哪一页。Next/router api 文档位于此处Nextjs Router API。

这是我正在尝试做的事情的一个简单示例:

const setHistory = () => {
    const { state } = window.history;
    const newState = {
        ...state,
        scroll: 'my custom scroll value'
    };
    history.replaceState(newState, '', state.url);
}

const handleRouteChangeStart = (url) => {
    setHistory();
}

const handlePopstate = () => {
    console.log(window.history)
}

window.addEventListener('popstate', handlePopstate);
Router.events.on('routeChangeStart', handleRouteChangeStart);
Run Code Online (Sandbox Code Playgroud)

我还尝试将值设置为 nextjs 设置的选项键,但结果与此不一致,这也意味着有时未设置该值,感觉有点 hacky。

NextJs 真的不允许您与浏览器历史记录进行任何类型的交互或操作 window.history 对象吗?