Router的问题Cannot read property 'location' of undefined

小刘
  • 526

项目的地址-->路由

main.js

import About from './Router/About'
import Repos from './Router/Repos'
import App from './Router/App'
import React from 'react'
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';



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

ReactDOM.render((
    <Router history={hashHistory}>
        <Route path="/" component={App}/>
        {/* add the routes here */}
        <Route path="/repos" component={Repos}/>
        <Route path="/about" component={About}/>
    </Router>
), document.getElementById('app'))

图片描述

回复
阅读 16.3k
4 个回答

react-router@v4.0:

  • React Router被拆分成三个包:react-router,react-router-domreact-router-native,目前网站搭建只需要引入react-router-dom即可;

  • 路由器组件无法接受两个及以上的子元素;

  • ...

更多改变可以查看官方文档

正确写法如下:

    import React from 'react'
    import ReactDOM from 'react-dom';
    import { HashRouter, Route, hashHistory, Switch } from 'react-router-dom'
    
    import About from './Router/About'
    import Repos from './Router/Repos'
    import App from './Router/App'
    
    const SliderComponent = () => (
      <Switch>
        <Route exact path='/' component={App} />
        <Route path="/repos" component={Repos}/>
        <Route path="/about" component={About}/>
      </Switch>
    )
    
    ReactDOM.render((
      <HashRouter history={hashHistory}>
        <SliderComponent />
      </HashRouter>
    ), document.getElementById('app'));

看你 package.json 里react-router 已经4.x了,优先去react-router官方文档看看各种例子~
阮一峰这文章里也写明了

clipboard.png

现在直接用react-router-dom就行了,参考官方例子

小宁同学又来了
  • -1
新手上路,请多包涵

还是报错呀
'react-router-dom' does not contain an export named 'hashHistory'.

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
宣传栏