我将React SSR和react-router-dom用于路由。当我点击链接时,应用会重新加载整个页面。我不想重新加载所有页面。我只需要加载选定的组件。
当我使用webpack-dev-server时,它工作正常。我该怎么办?
import express from 'express';
import React from 'react';
import {renderToString} from 'react-dom/server';
import App from '../shared/App';
import {StaticRouter} from 'react-router-dom';
const app = express();
app.use(express.static("public"));
app.get('*', (req, res, next) => {
//console.log(req.url)
const context = {};
const markup = renderToString(
<StaticRouter location={req.url} context={context} >
<App />
</StaticRouter>
);
res.send(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>React SSR</title>
<link rel="stylesheet" href="/css/main.css" />
</head>
<body>
<div id="root">${markup}</div>
<script src="index_bundle.js"></script>
</body>
</html>
`)
})
app.listen(process.env.PORT || 3000, () => {
console.log("Server is listening");
})
浏览器/index.js。 我还在browser / index.js中使用BrowserRouter。
import React, { Component } from "react";
import {hydrate, render} from 'react-dom';
import {
BrowserRouter as Router
} from "react-router-dom";
import App from '../shared/App';
//console.log(process.env.calisma_turu)
if(process.env.appType == 'normal'){
render(
<Router>
<App />
</Router>, document.getElementById('root'));
}
if(process.env.appType == 'ssr'){
hydrate(
<Router>
<App />
</Router>, document.getElementById('root'));
}
应用组件在下面,我使用链接,路由具有Component属性。
import React, { Component } from "react";
import {
BrowserRouter as Router,
Switch,
Route,
Link
} from "react-router-dom";
import "./App.css";
import "./AppLogin.scss";
import Home from './Home';
import About from './About';
import Dashboard from './Dashboard';
class App extends Component {
render(){
return(
<div>
<div className="router-cont">
<ul>
<li>
<Link to="/" >Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/dashboard">Dashboard</Link>
</li>
</ul>
<br/><br/>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/dashboard" component={Dashboard} />
</Switch>
</div>
<div className="app">
<div className="app-header">
<h2>Welcome to React SSR</h2>
</div>
</div>
</div>
)
}
}
export default App;
App可以正常加载我的页面,但可以重新加载所有页面。我只需要加载选定的组件,而不是整个页面。