无法读取未定义的 属性 'location'

Cannot read property 'location' of undefined

我尝试使用 react-router-dom 4.0.0 库。但它向我发送了这个错误

Uncaught TypeError: Cannot read property 'location' of undefined

看来问题出在browserHistore。在我使用 react-router 2.x.x 之前一切正常。 这是我的 index.js

import 'babel-polyfill'
import React from 'react'
import { Router, hashHistory } from 'react-router-dom'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { configureStore } from './store'
import { routes } from './routes'

const store = configureStore()

render(
  <Provider store={store}>
    <Router history={hashHistory} routes={routes} />
  </Provider>,
  document.getElementById('root')
)

这是我的路线

import React from 'react'
import { IndexRoute, Route } from 'react-router-dom'
import App from './containers/App'
import Main from './containers/Main'
import First from './containers/First'

export const routes = (
  <Route path='/' component={Main}>
    <Route path='/path' component={First} />
    <IndexRoute component={App} />
  </Route>
  )

对于服务器端快递,我设置了这个获取配置

app.get('*', function root(req, res) {
  res.sendFile(__dirname + '/index.html');
});

React Router v4 是完全重写的,并且与您在代码中假设的先前版本不兼容。话虽如此,您不应该期望能够只升级到新的主要版本 (V4) 并让您的应用程序正常工作。您应该查看 documentation 或降级回 V2/3。这里有一些代码可以让您朝着正确的方向开始

import 'babel-polyfill'
import React from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { configureStore } from './store'
import App from './containers/App'
import Main from './containers/Main'
import First from './containers/First'

const store = configureStore()

render(
  <Provider store={store}>
    <Router>
      <Route path='/' component={Main} />
      <Route path='/path' component={First} />
    </Router>
  </Provider>,
  document.getElementById('root')
)
  1. 检查package.json

  2. 中react-router-dom的版本
  3. 如果它的版本大于 4 那么在你的文件中导入 BrowserRouter :-

    import { BrowserRouter as Router, Route } from 'react-router-dom'
    

    否则如果它的版本小于 4 然后导入路由器 :-

    import { Router, Route } from 'react-router-dom'
    

安装npm history packagenpm i history

然后在您的 index/routes 文件中使用它:

import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Switch, Route} from 'react-router-dom';
import createBrowserHistory from 'history/createBrowserHistory';
import App from './components/App';
import './index.css'

const history = createBrowserHistory();

ReactDOM.render(
    <Router history={history}>
        <Switch>
            <Route path='/' component={App}/>
        </Switch>
    </Router>,
     document.getElementById('root')
    );