使用 Redux 时 Next.js 不需要浏览器历史记录吗?

Does Next.js not need browser history when using Redux?

我正在尝试将我的 React 应用程序迁移到 Next.js。我的 configureStore.js.

中一直有来自 export const history = createBrowserHistory(); 的错误

Invariant Violation: Browser history needs a DOM

configureStore.js

import { createStore, combineReducers, compose, applyMiddleware } from "redux";
import { connectRouter, routerMiddleware } from "connected-react-router";
import { createBrowserHistory } from "history";
import thunk from "redux-thunk";
import user from "./modules/user";
import stores from "./modules/stores";
import info from "./modules/info";

export const history = createBrowserHistory();

const middlewares = [thunk, routerMiddleware(history)];

const reducer = combineReducers({
  user,
  stores,
  info,
  router: connectRouter(history)
});

export default function configureStore(preloadedState) {
  return createStore(
      reducer,
      preloadedState,
      compose(
        applyMiddleware(
          ...middlewares
        )
      )
    );
}

我发现在将 React 迁移到 Next.js 时需要更改很多东西,因为 Next 是一个框架,需要自己的代码架构以及 SSR 和 CSR 之间的区别。我在学习Next.js教程的时候,有一个路由部分说路由是根据CSR或SSR来区分的。这是否意味着我不能在 Next.js 中使用浏览器历史记录?这就是我的猜测。我还是一头雾水。

你是对的。 SSR和CSR是有区别的。 Next.js 使用 Next Router 为 CSR 路由,如果您需要自定义 SSR,那么您应该向 express.

等框架寻求帮助

通过执行 CSR,nextjs 将记住浏览器历史记录并且后退按钮按预期工作。但是,如果您需要将路线更改为非常不同的路线,您可以使用以下任何一种解决方案:

import Router from 'next/router';
...
Router .push('/about');

或者

import Link from 'next/link';
...
<Link href="/about"><a>about</a></Link>

如果您需要在路由之前做一些额外的工作,那么您应该使用:

Router.beforePopState(({ url, as, options }) => {...}

迁移需要一些时间,您需要记住 next.js 将自动接管路由和浏览器历史记录。除非你自定义它。