createMemoryHistory仍报告“浏览器历史记录需要DOM”

时间:2018-11-26 23:35:46

标签: javascript reactjs redux react-router react-router-v4

我收到的错误出于各种目的,我认为我不应该:)

流为

客户 history.js> client/index.js> history = createBrowserHistory> <App history={history} />

服务器 history.js> server/index.js> history = createMemoryHistory> <App history={history} />

我可以确认服务器上正在使用内存,然后内存就掉了,所以我们再也无法进入BroswerHistory

server.js中的错误

Invariant Violation: Browser history needs a DOM

  30 | 
  31 |          // Render the component to a string
> 32 |          const markup = renderToString(
  33 |              <Provider store={store}>
  34 |                  <App history={history} />
  35 |              </Provider>

history.js

import createBrowserHistory from 'history/createBrowserHistory'
import createMemoryHistory from 'history/createMemoryHistory'

let history
let createHistory

if (typeof document !== 'undefined') {
    createHistory = createBrowserHistory
} else {
    createHistory = createMemoryHistory
}
history = createHistory()

export default history

我已经检查并确保<BrowserRouter />也不是错误的地方。

routes.js

const routes = (
    <Fragment>
        <BrowserRouter>
            <Switch>
                <Route component={NoMatch} />
            </Switch>
        </BrowserRouter>
    </Fragment>
)

export default routes

server.js

 import history from '../common/history'

 const store = configureStore(preloadedState, history)

// Render the component to a string
const markup = renderToString(
    <Provider store={store}>
        <App history={history} />
    </Provider>
)

App.js

import React from 'react'
import PropTypes from 'prop-types'
import { ConnectedRouter } from 'connected-react-router'
import routes from '../routes'

const App = ({ history }) => {
    return <ConnectedRouter history={history}>{routes}</ConnectedRouter>
}

App.propTypes = {
    history: PropTypes.object
}

export default App

1 个答案:

答案 0 :(得分:2)

BrowserRouter组件创建自己的history对象,并且始终是HTML5 history API,在非DOM环境中,例如,服务器。

您可以构建应用程序,使其不包含服务器上的BrowserRouter,也可以将其替换为Router组件,然后将其传递给您自己的history对象,该对象将使用内存非DOM环境中的历史记录。

const routes = (
    <Fragment>
        <Router history={history}>
            <Switch>
                <Route component={NoMatch} />
            </Switch>
        </Router>
    </Fragment>
)