我使用react-router和服务器端rending。但是我的服务器端不能与路由器一起使用。它更改URL,但不呈现组件 我的服务器端代码:
VM.h
这是我的应用代码:
import express from 'express';
import cors from "cors";
import { renderToString } from "react-dom/server";
import App from '../shared/App';
import React from 'react';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import rootReducer from "../shared/reducers/index";
import { StaticRouter, matchPath } from "react-router-dom"
import { create } from 'domain';
const app = express();
app.use(express.static("public"));
app.use(cors());
app.use("*", (req, res, next) => {
let context = {};
const store = createStore(rootReducer)
const markup = renderToString(
<Provider store = {store}>
<StaticRouter location={req.url} context={context}>
<App />
</StaticRouter>
</Provider>
)
const preloadedState = store.getState();
res.send(`
<!DOCTYPE html>
<html>
<head>
<title>SSR with RR</title>
</head>
<body>
<div id="app">${markup}</div>
<script>
window.__PRELOADED_STATE__ = ${JSON.stringify(preloadedState)}
</script>
<script src = "/bundle.js"></script>
</body>
</html>
`)
});
app.listen(3000, () => {
console.log('Server is running ....')
});
我的List和Home组件呈现字符串“ Home”和“ List” 我的index.js代码
import React from 'react';
import { Route } from 'react-router-dom';
import List from "./List";
import { Link } from 'react-router-dom';
import Home from './Home';
import { connect } from "react-redux";
class App extends React.Component {
render() {
return (
<div>
Hello
<ul>
<li><Link to="/list">List</Link></li>
<li><Link to="/home"> Home</Link></li>
</ul>
<Route component={List} path="/list" />
<Route component={Home} path="/home" exact />
</div>
);
}
};
export default connect(null,null)(App);
这是我所有的代码,但更改了网址,但未加载组件
答案 0 :(得分:0)
解决了问题,我必须将withRouter从react-router-dom添加到应用程序组件
withRouter(connect(null,null)(App));