React 上的路由,TypeError:无法读取 undefined(...) 的属性“getCurrentLocation" [英] Routes on React, TypeError: Cannot read property 'getCurrentLocation' of undefined(…)
问题描述
我正在尝试使用 ReactJS 进行基本操作,并且正在尝试了解如何使用 React-Router
I'm trying basic stuff with ReactJS and I'm trying to understand how to work with 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'未定义(…)
Uncaught TypeError: Cannot read property 'getCurrentLocation' of undefined(…)
我正在使用 webpack 将 jsx 编译成 js,我错过了什么?(顺便说一句,webpack 没有错误)
I'm using webpack to compile the jsx into js, what am I missing ? (btw no error from the webpack)
谢谢!
推荐答案
您缺少路由器的历史定义尝试:
You're missing the history definition for your Router try:
<Router history={hashHistory|browserHistory|createMemoryHistory}>
<Route path="/" component={Home} />
</Router>
注意:您必须使用 React 路由器将所选的历史记录类型添加到导入中,因此如果您选择添加 browserHistory,您的导入将如下所示:
NB: You'll have to add the chosen history type to your imports with React router, so if you choose to add browserHistory your import would look something like this:
import { browserHistory, Router, Route } from 'react-router'
^---added as a named import
<小时>
对不同选项的简要说明:
browserHistory:基础以路线/"开头的完整网址的路径.因此,如果您的 SPA 位于 www.myapp.com,则默认情况下根路径将对应 www.myapp.com/
.所以如果你想要一个到 www.myapp.com/blog
的路由,你需要定义一个路由路径/blog
".
browserHistory : bases your path of the full url starting with the route '/'. So if your SPA is at www.myapp.com, the root path will coorespond to www.myapp.com/
by default. So if you wanted a route to www.myapp.com/blog
, you would need to define a router path of '/blog
'.
hashHistory:是否同样的事情,但根从 url 中找到的第一个 #
字符开始: example.com/#/some/path
将对应于: /some/path
hashHistory: does the same thing but the root starts from the the first #
character found in the url: example.com/#/some/path
would correspond to: /some/path
createMemoryHistory:使用用于测试和服务器渲染.此选项不会读取或地址栏.
createMemoryHistory: used for testing and for server rendering. This option does not read from or manipulate the address bar.
查看:反应路由器历史 了解更多信息
这篇关于React 上的路由,TypeError:无法读取 undefined(...) 的属性“getCurrentLocation"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!