【问题标题】:react router basic example gives error Cannot resolve module 'history/lib/createBrowserHistory'反应路由器基本示例给出错误无法解析模块'history/lib/createBrowserHistory'
【发布时间】:2018-04-25 17:15:26
【问题描述】:

按照 react 培训文档学习 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: 编译成功。

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

在搜索问题后,与其他 solution suggested 一起指出 React Router 是基于历史构建的。

试了一下

    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 时出现错误

找不到模块:错误:无法解析模块 'history/lib/createBrowserHistory' 在 /opt/react-router-tutorial/lessons/01-setting-up

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

【问题讨论】:

  • 您所遵循的教程似乎已过时,您可能需要遵循official documentation 中的示例。该软件包现在称为 react-router-dom 顺便说一句。

标签: react-router


【解决方案1】:

您所遵循的教程已过时。基本上,有各种类型的路由器组件(BrowserRouter、HashRouter等),它们自己管理自己的历史。

也就是说,如果您使用的是react-router-dom。你看,react-router 现在是react-router-domreact-router-native 都使用的核心包,你应该安装其中一个(在这种情况下,可能是react-router-dom)。

然后您可以像这样更改您的代码(假设渲染函数来自某个地方,大概是 react-dom):

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

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

【讨论】:

  • 当运行 npm install react-router-dom --save-dev 时,它会在终端中出现错误,因为 UNMET PEER DEPENDENCY webpack@3.8.1 。虽然项目运行良好,但我需要担心吗?
  • 我已经点击了您提供的链接,现在遇到了这个问题。你能看看这个并帮助我吗:stackoverflow.com/questions/47263714/…
【解决方案2】:

^4.7.2版本的'history'改变了源码路径,或许你可以试试:

import createBrowserHistory from 'history/es/createBrowserHistory';

const appHistory = createBrowserHistory()

【讨论】:

    猜你喜欢
    • 2017-04-05
    • 2019-08-23
    • 2019-05-01
    • 2015-09-03
    • 2018-01-20
    • 2020-08-27
    • 2021-11-29
    • 2016-05-08
    • 2020-01-07
    相关资源
    最近更新 更多