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

Jay*_*Jay 1 next.js

我正在尝试将我的React应用程序迁移到Next.js. 我一直低于误差来自export const history = createBrowserHistory();于我的configureStore.js

不变违规:浏览器历史记录需要一个 DOM

配置Store.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
        )
      )
    );
}
Run Code Online (Sandbox Code Playgroud)

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

MoH*_*oHo 5

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

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

import Router from 'next/router';
...
Router .push('/about');
Run Code Online (Sandbox Code Playgroud)

或者

import Link from 'next/link';
...
<Link href="/about"><a>about</a></Link>
Run Code Online (Sandbox Code Playgroud)

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

Router.beforePopState(({ url, as, options }) => {...}
Run Code Online (Sandbox Code Playgroud)

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