栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

这个ReactRouter.match()实现有什么问题?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

这个ReactRouter.match()实现有什么问题?

如果您在v4之前使用了react router,那么您的代码看起来是正确的,但是react-router
v4在整个代码库中都有重大更改,包括服务器渲染方法。在v4中,有一个专门用于服务器渲染的新组件-

StaticRouter

您的代码在v4中应如下所示:

import path from "path";import { Server } from "http";import Express from "express";import React from "react";import { renderToString } from "react-dom/server";import { StaticRouter } from "react-router";import App from "./app";import NotFoundPage from "./components/NotFoundPage";// Initialize the express server, and tell it to use ejsconst app = new Express();const server = new Server(app);app.set("view engine", "ejs");app.set("views", path.join(__dirname, "views"));// Tell express where the static assets areapp.use(Express.static(path.join(__dirname, "static")));app.get("*", (req, res) => {  // This context object contains the results of the render  const context = {};  const html = renderToString(    <StaticRouter location={req.url} context={context}>      <App />    </StaticRouter>  );  res.status(200).send(html);});const port = process.env.PORT || 3000;const env = process.env.NODE_ENV || "production";server.listen(port, err => {  if (err) {    return console.error(err);  }  console.info(`Server running on http://localhost:${port} [${env}]`);});

这是EbayTech的一篇非常好的带注释的文章,显示了如何使用StaticRouter(用于服务器)和BrowserRouter(用于客户端)设置应用程序



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/398012.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号