反应路由器基本示例给出错误无法解析模块' history / lib / createBrowserHistory'

时间:2017-11-13 04:53:17

标签: react-router

通过反应培训文档来学习react-router的基础知识,但在第一个例子中失败了。下面是我的 package.json 信息

    "dependencies": {
        "history": "^4.7.2",
        "react": "^0.14.7",
        "react-dom": "^0.14.7",
        "react-router": "^2.0.0"
    },

这是 index.js 文件

中的相关代码
    import { Router, Route, hashHistory } from 'react-router'

    render((
      <Router history={hashHistory}>
        <Route path="/" component={App}/>
      </Router>
    ), document.getElementById('app'))

npm start输出 webpack:已成功编译。

但是在broswer页面中打开了一个URL http://localhost:8080/#/?_k=hrfoj1 中的随机垃圾,并且在浏览器上没有显示任何内容

在搜索问题后,其他solution suggested附带了React路由器建立在历史记录上。

所以试过这个

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

    import createBrowserHistory from 'history/lib/createBrowserHistory'
    const appHistory = createBrowserHistory()

    render((<Router history={appHistory} > ...</Router>),  document.getElementById('app'));

但是当运行npm start时会出现错误

  

找不到模块:错误:无法解析模块   &#39;的历史/ lib目录/ createBrowserHistory&#39;在   的/ opt /反应路由器教程/经验/ 01-的建立

所以请告诉我什么是正确的解决方案

2 个答案:

答案 0 :(得分:1)

The tutorial you are following is outdated. Basically, there are various types of router components (BrowserRouter, HashRouter, etc.) and they manage their history by themselves.

That is, if you are using react-router-dom. You see, react-router is now a core package which is used by both react-router-dom and react-router-native and you should install one of those (in this case, probably react-router-dom).

You can then change your code like this (assuming that the render function is coming from somewhere, presumably react-dom):

// notice the different package here
import { BrowserRouter, Route } from 'react-router-dom'

render((
  <BrowserRouter>
    <Route path="/" component={App}/>
  </BrowserRouter>
), document.getElementById('app'))

答案 1 :(得分:1)

^ 4.7.2版本的'历史'已经改变了源路由,也许你可以试试:

import createBrowserHistory from 'history/es/createBrowserHistory';

const appHistory = createBrowserHistory()