【问题标题】:Routing problem in React-JS / react-router-domReact-JS / react-router-dom 中的路由问题
【发布时间】:2019-03-17 06:21:54
【问题描述】:

我通过在命令提示符窗口中运行以下代码 sn-p 在我的项目上安装了react-router

npm install react-router

我发现react-router安装成功,因为安装没有错误,而且输出是:

  • 反应路由器@4.3.1 在 19.53 秒内更新了 1 个包

基于tutorial,我将我的Index.js 设置为如下代码:

ReactDOM.render((
   <Router history = {browserHistory}>
      <Route path = "/" component = {App}>
         <IndexRoute component = {Home} />
         <Route path = "home" component = {Home} />
         <Route path = "about" component = {About} />
         <Route path = "contact" component = {Contact} />
      </Route>
   </Router>
), document.getElementById('app'))

现在当我想编译/构建我的应用程序时,会出现以下错误:

./src/index.js
  Line 14:  'Router' is not defined          react/jsx-no-undef
  Line 14:  'browserHistory' is not defined  no-undef
  Line 15:  'Route' is not defined           react/jsx-no-undef
  Line 16:  'IndexRoute' is not defined      react/jsx-no-undef
  Line 17:  'Route' is not defined           react/jsx-no-undef
  Line 18:  'Route' is not defined           react/jsx-no-undef
  Line 19:  'Route' is not defined           react/jsx-no-undef

我知道编译器找不到路由类,我已经在 google 和这个社区上搜索过我的问题之类的问题,但实际上我的搜索结果没有帮助。感谢您的回复。

【问题讨论】:

    标签: reactjs routing react-router react-router-v4 react-router-dom


    【解决方案1】:

    您需要在调用它们之前将Router、Route和index.js文件中导入

     import { Router, Route } from "react-router";
    

    React-Router v4 不支持 IndexRoute,您可以使用 Route 精确代替 IndexRoute,例如

      <Route exact path={path} component={Component} />
    

    编辑:

    react-router v4 不支持browserHistory,所以这里有替代解决方案检查https://github.com/ReactTraining/react-router/blob/25776d4dc89b8fb2f575884749766355992116b5/packages/react-router/docs/guides/migrating.md#the-router

    【讨论】:

    • 我的 6 个错误已解决,但 RouterIndex 有问题:“编译失败。./src/index.js 尝试导入错误:'IndexRoute' 未从 'react-router' 导出。”
    • Hey IndexRoute 似乎已在 React-Router v4 中删除,因此请检查我更新的解决方案以获取替代
    • 谢谢,我用 IndexRouter 将 Router 替换为 'exact' 属性,我的问题解决了,但是 browingHistory 呢? React-Router v4 不支持它吗?因为我也有问题:“./src/index.js Attempted import error: 'browserHistory' is not export from 'react-router'。”
    • 不客气。我已经更新了我的答案,请检查
    猜你喜欢
    • 2022-06-15
    • 1970-01-01
    • 2019-01-15
    • 2020-10-14
    • 2020-04-14
    • 1970-01-01
    • 2022-01-09
    • 2019-05-30
    • 1970-01-01
    相关资源
    最近更新 更多