reactjs - 如何在不使用“react-router-dom”进行 SSR 时检测 404 路由(NoMatch)?
问题描述
我正在使用react-router-dom
并且正在为我的 Web 应用程序实现SSR(服务器端渲染)。
我在如何处理404
路线上遇到了麻烦。
我的目标:
- 每当有人访问
/non-existent-route
我的网络应用程序时。我不想重定向它们。他们应该保持在同一条路线上,并且应该HTTP status 404
与404 Page
.
这应该是顺序:
REQ GET /non-existent-route
RES 404 /non-existent-route
连同用于404 Page
例子:
用户尝试访问与任何路由都不匹配的路径。
它应该被我的最后一个“捕获”<Switch>
<Route>
并被Page404
渲染。就像官方文档中的这个例子一样。
<Switch>
<Route exact path={"/route1"} component={Component1}/>
<Route exact path={"/route2"} component={Component2}/>
<Route path={"*"} component={Page404}/>
</Siwtch>
当我使用renderToString
from渲染它时react-dom/server
,这就是我所做的:
来自:反应路由器文档
如果我将其重定向到 404,我可以使用context.url
来检测是否发生了重定向(如以下文档中的示例)。但我不想重定向。我想404
在同一条路线上返回状态。因此我不能context.url
用来检测 404 路由。
问题
Page404
当我没有从渲染重定向时,如何检测没有匹配的特定路由和渲染?
解决方案
刚刚发现如何做到这一点。
从官方文档中我们得到:
您可以将信息添加到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
)。正如预期的那样:
推荐阅读
- iphone - 希望我的 iPhone 应用程序最初是免费的,以后用户需要付费才能继续使用
- ios - 从 SafariWebController 返回时的 Swift 白屏
- java - 如何在可视化排序算法中“正确”使用 Swing Timer
- vue.js - 如何使用axios将vue中的表单数据作为json发送到变量?
- javascript - 在页面重新加载后保持活动选项卡时加载 ajax 内容(Bootstrap 4)
- python-3.x - SyntaxError: invalid syntax - 定义函数的参数
- azure - 在 IdentityServer4 上具有共享回调路径的多个 Azure AD 租户
- javascript - ANT 是否支持地图(Javascript)?
- php - 在 PHP Codeigniter 中检索一个月的 1 到 31 之间的 num 行数据
- powerbi - 单击表格可视 Power BI 上的单元格后向下钻取