我遇到了同樣的問題。
我是新來的節點,但如果你檢查node_modules文件夾,以及爲react-router v4 documentation,有一個ServerRouter類不提,像一個堪稱client.js文件。
可能是創建createServerRenderContext函數也不存在。至少不在這個模塊中。
嘗試用代替那個StaticRouter也許。
編輯:
管理,使其通過安裝最新版本ReactRouter 4測試版的
npm install --save [email protected]
npm install --save [email protected]
然後改變server.js文件工作:
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import {StaticRouter} from 'react-router';
import {createStore, applyMiddleware} from 'redux';
import thunkMiddleware from 'redux-thunk';
import {Provider} from 'react-redux';
import serialize from 'serialize-javascript';
import reducer from './reducers';
import App from 'components/App';
window.render = (template, model) => {
const context = {};
const req = JSON.parse(model.get('req'));
const initialState = JSON.parse(model.get('initialState'));
const store = createStore(reducer, initialState, applyMiddleware(thunkMiddleware));
const markup = ReactDOMServer.renderToString(
<Provider store={store}>
<StaticRouter location={req.location} context={context}>
<App/>
</StaticRouter>
</Provider>
);
return template
.replace('SERVER_RENDERED_HTML', markup)
.replace('SERVER_RENDERED_STATE', serialize(initialState, {isJSON:true}));
};
客戶端.js與:
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom';
import {createStore, applyMiddleware} from 'redux';
import thunkMiddleware from 'redux-thunk';
import {Provider} from 'react-redux';
import reducer from './reducers';
import App from 'components/App';
const store = createStore(reducer, window.__PRELOADED_STATE__, applyMiddleware(thunkMiddleware));
const markup = (
<Provider store={store}>
<BrowserRouter>
<App/>
</BrowserRouter>
</Provider>
);
ReactDOM.render(markup, document.getElementById('app'));
最後的App.js
import React from 'react';
import {Route, Link} from 'react-router-dom';
import Home from 'components/Home';
import Child from 'components/Child';
import 'styles/main.css';
export default function App() {
return (
<div>
<h1>Hello Server Side Rendering!!</h1>
<ul>
<li><Link to="/">{'Home'}</Link></li>
<li><Link to="/child">{'Child'}</Link></li>
</ul>
<Route exactly path="/" component={Home}/>
<Route path="/child" component={Child}/>
</div>
);
}
我刪除了小姐的對象,因爲它沒有在這個版本的反應路由器
感謝您的回覆!我已經使用您的文章進行設置。問題在於,需要提供服務器的應用程序使用react-router v3,這會導致一些問題。感謝您的幫助! –