首页 > 解决方案 > 如何在不使用“react-router-dom”进行 SSR 时检测 404 路由(NoMatch)?

问题描述

我正在使用react-router-dom并且正在为我的 Web 应用程序实现SSR(服务器端渲染)。

我在如何处理404路线上遇到了麻烦。

我的目标:

这应该是顺序:

例子:

用户尝试访问与任何路由都不匹配的路径。

它应该被我的最后一个“捕获”<Switch> <Route>并被Page404渲染。就像官方文档中的这个例子一样。

<Switch>
  <Route exact path={"/route1"} component={Component1}/>
  <Route exact path={"/route2"} component={Component2}/>
  <Route path={"*"} component={Page404}/>
</Siwtch>

当我使用renderToStringfrom渲染它时react-dom/server,这就是我所做的:

来自:反应路由器文档

在此处输入图像描述

如果我将其重定向到 404,我可以使用context.url来检测是否发生了重定向(如以下文档中的示例)。但我不想重定向。我想404在同一条路线上返回状态。因此我不能context.url用来检测 404 路由。

在此处输入图像描述


问题

Page404当我没有从渲染重定向时,如何检测没有匹配的特定路由和渲染?

标签: reactjsreact-routerhttp-status-code-404react-router-domserver-side-rendering

解决方案


刚刚发现如何做到这一点。

官方文档中我们得到:

您可以将信息添加到staticContext. context即使您不<Redirect/>从渲染中,该信息也会添加到对象中。

在此处输入图像描述

这是带有此示例的CodeSandbox :

应用程序.tsx

import * as React from "react";
import { Switch, Route } from "react-router-dom";
import "./styles.css";

export default function App() {
  return (
    <Switch>
      <Route
        path={"*"}
        render={({ staticContext }) => {
          if (staticContext) {
            staticContext.statusCode = 404;
          }
          return <div>WHATEVER</div>;
          // return <Redirect to="/404" />;
        }}
      />
    </Switch>
  );
}

索引.tsx

import * as React from "react";
import { StaticRouter } from "react-router-dom";
import { renderToString } from "react-dom/server";
import App from "./App";

// ON THE SERVER
const context = {};

const html = renderToString(
  <StaticRouter location={"/"} context={context}>
    <App />
  </StaticRouter>
);

console.log(JSON.stringify(context));

这是结果(从 记录index.tsx)。正如预期的那样:

在此处输入图像描述


推荐阅读