【问题标题】:Routes on React, TypeError: Cannot read property 'getCurrentLocation' of undefined(…)React 上的路由,TypeError:无法读取未定义的属性“getCurrentLocation”(…)
【发布时间】:2016-12-07 17:24:06
【问题描述】:

我正在尝试使用 ReactJS 进行基本操作,并且正在尝试了解如何使用 React-Router

这是我的代码:

var React = require('react');
var ReactDOM = require('react-dom');
var Router = require('react-router').Router;
var Route = require('react-router').Route;

const Home = React.createClass({
  render: function() {
    return (<h1>Welcome to the Home Page</h1>);
  }
});

ReactDOM.render((
    <Router>
      <Route path="/" component={Home} />
    </Router>
), document.getElementById('root')); 

我不断收到以下错误:

未捕获的类型错误:无法读取属性“getCurrentLocation”的 未定义(…)

我正在使用 webpack 将 jsx 编译成 js,我缺少什么? (顺便说一句,webpack 没有错误)

谢谢!

【问题讨论】:

    标签: reactjs react-router


    【解决方案1】:

    您缺少路由器尝试的历史定义:

    <Router history={hashHistory|browserHistory|createMemoryHistory}>
      <Route path="/" component={Home} />
    </Router>

    注意:您必须使用 React 路由器将所选的历史记录类型添加到您的导入中,因此如果您选择添加 browserHistory,您的导入将如下所示:

    import { browserHistory, Router, Route } from 'react-router'
               ^---added as a named import

    不同选项的简要说明:

    browserHistory :以路径“/”开头的完整 url 的路径为基础。因此,如果您的 SPA 位于 www.myapp.com,则根路径将默认对应于 www.myapp.com/。所以如果你想要一个到www.myapp.com/blog的路由,你需要定义一个路由路径'/blog'。

    hashHistory:做同样的事情,但根从 URL 中的第一个 # 字符开始:example.com/#/some/path 对应于:/some/path

    createMemoryHistory:用于测试和服务器渲染。此选项不读取操作地址栏。

    查看:React Router Histories 了解更多信息

    【讨论】:

    • 我尝试添加另一个名为 Testit 的类,所以路由现在看起来像这样 ` ` 当我转到 localhost:3030/test 时没有显示任何内容,但是当我转到 / 时,我可以看到 Home 组件我现在缺少什么?非常感谢!
    • 您应该将/test 路径嵌套在 Home 路径中,如下所示:&lt;Router history={browserHistory}&gt; &lt;Route path="/" component={Home} &gt; &lt;Route path="/test" component={Testit} /&gt;&lt;/Route&gt; &lt;/Router&gt;
    • 我现在试过了,我得到了 404 页 pastebin.com/Gsjy4TEs
    • 这个问题可能会有所帮助。 github.com/ReactjsProgram/React-Fundamentals/issues/36
    猜你喜欢
    • 2021-10-19
    • 1970-01-01
    • 2015-05-25
    • 1970-01-01
    • 2023-04-01
    • 2021-12-31
    • 1970-01-01
    • 2018-10-17
    • 2019-12-05
    相关资源
    最近更新 更多