Skip to content

Commit

Permalink
type: add 引入路由
Browse files Browse the repository at this point in the history
1、客户端用的路由是 BrowserRouter import { BrowserRouter } from "react-router-dom";
2、服务器端路由是 StaticRouter   import { StaticRouter } from "react-router-dom/server";
  • Loading branch information
bin.zhang02 committed Jan 16, 2022
1 parent 63ec354 commit 05db320
Show file tree
Hide file tree
Showing 5 changed files with 109 additions and 6 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
"express": "^4.17.2",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "^6.2.1",
"save": "^2.4.0",
"webpack": "^5.66.0",
"webpack-cli": "^4.9.1",
Expand Down
81 changes: 80 additions & 1 deletion public/index.js

Large diffs are not rendered by default.

11 changes: 11 additions & 0 deletions src/Routes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import React from "react";
import { Route, Routes } from "react-router-dom";
import Home from "./containers/Home/index";

export default (
<div>
<Routes>
<Route path="/" exact element={<Home />} />
</Routes>
</div>
);
8 changes: 7 additions & 1 deletion src/client/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import React from "react";
import ReactDom from "react-dom";
import Home from "../containers/Home";
import { BrowserRouter } from "react-router-dom";
import Routes from "../Routes";

ReactDom.hydrate(<Home />, document.getElementById("root"));
const App = () => {
return <BrowserRouter>{Routes}</BrowserRouter>;
};

ReactDom.hydrate(<App />, document.getElementById("root"));
14 changes: 10 additions & 4 deletions src/server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,10 @@ const express = require("express");
const app = express();
const port = 3000;
import React from "react";
import { StaticRouter } from "react-router-dom/server";
import { renderToString } from "react-dom/server";

import Home from "../containers/Home/index";

const content = renderToString(<Home />);
import Routes from "../Routes";
// import Home from "../containers/Home/index";

// express的中间件, public是根目录下的
// 以 .js 结尾的是静态文件
Expand All @@ -15,6 +14,13 @@ const content = renderToString(<Home />);
app.use(express.static("public"));

app.get("/", (req, res) => {
// location={req.path} 这个是必须的,原因是服务器端无法感觉浏览器的地址,所以需要获取地址
const content = renderToString(
<StaticRouter location={req.path} context={{}}>
{Routes}
</StaticRouter>
);

res.send(`
<html>
<head></head>
Expand Down

0 comments on commit 05db320

Please sign in to comment.