开发者问题收集

无法读取未定义的属性“位置”

2017-04-01
42189

我尝试使用 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>
  )

此外,对于服务器端 express,我设置了这个获取配置

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

React Router v4 是完全重写的,与代码中假设的以前的版本不兼容。话虽如此,您不应该期望能够升级到新的主版本 (V4) 并让您的应用正常工作。您应该查看 文档 或降级回 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')
)
Tyler McGinnis
2017-04-01
  1. 检查 package.json 中的 react-router-dom 版本

  2. 如果其版本大于 4,则在您的文件中导入 BrowserRouter :-

    从 'react-router-dom' 导入 { BrowserRouter as Router, Route }
    

    否则,如果其版本小于 4,则导入 Router :-

    从 'react-router-dom' 导入 { Router, Route }
    
MERLIN THOMAS
2017-11-13

安装 npm history 包 npm 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')
    );
Sodik Abdullaev
2019-05-29