我正在尝试使用react-router v4,redux和express为我的应用程序呈现内容,但终端中出现Browser history needs a DOM
错误。我还使用react-router-config来保持我的路线更有条理。看到一个解决方案,建议应该在服务器上创建存储,所以我尝试将store.js文件中的代码复制到服务器,但是它没有成功。我该怎么做才能解决这个非常不愉快的错误?
routes.js
const routes = (
{
component: App,
routes: [
{
path: '/',
exact:true,
component: Home
},
{
path: '/login',
exact:true,
component: Login
},
{
path: '/registration',
exact:true,
component: Registration
},
{
path: '/person/:id',
exact:true,
component: UserPage
},
{
path: '/myPage',
exact:true,
component: MyPage
},
{
path: '/goodBye',
exact:true,
component: GoodBye
},
{
path: '*',
component: NoMatch
}
]
}
);
App.js
import React from 'react';
import ReactDOM from 'react-dom';
//import '../styles/app.scss'
import {Provider} from 'react-redux';
import {Grid} from 'react-bootstrap';
import store from './store/store';
import routes from './routes';
import { createBrowserHistory } from 'history';
import { syncHistoryWithStore } from 'react-router-redux';
import { renderRoutes } from 'react-router-config';
import { BrowserRouter as Router} from 'react-router-dom';
import { ConnectedRouter, Switch } from 'connected-react-router';
class App extends React.Component {
render() {
return (
<Provider store={store}>
<Grid fluid={true}>
<ConnectedRouter history={createBrowserHistory()}>
<Switch>
{renderRoutes(routes)}
</Switch>
</ConnectedRouter>
</Grid>
</Provider>
);
}
}
const isBrowser = typeof window !== 'undefined';
if(isBrowser) {
ReactDOM.render(<App/>, document.getElementById('root'));
}
路线处理程序:
import express from 'express';
import React, {Component} from 'react';
import { renderToString } from 'react-dom/server';
import routes from '../../js/routes';
import {StaticRouter} from 'react-router';
import { renderRoutes } from 'react-router-config';
import { Provider } from 'react-redux';
import store from '../../js/store/store';
const router = express.Router();
router.get('*',(req,res) => {
let context = {};
const content = renderToString(
<Provider store={store}>
<StaticRouter location={req.url} context={context}>
{renderRoutes(routes)}
</StaticRouter>
</Provider>
);
if(context.status === 404) {
res.status(404);
}
res.render('index', {title: 'Express', data: store.getState(), content });
});