我正在学习 React,我需要使用 React Routes 添加一些路由。
我已经安装了 react-router
和 npm install react-router
。
这是 main js
我必须在其中声明路线
import React from 'react';
import {ReactDOM, render} from 'react-dom';
import App from './Components/AppComponent';
import Example from './Components/ExampleComponent';
import { Router, Route, IndexRoute, Link, IndexLink, browserHistory } from 'react-router'
render((
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="example" component={Example}/>
</Route>
</Router>
), document.getElementById('App'));
导航到 /
工作正常。但是当我去 /example
我得到:
无法获取
/example
错误
我究竟做错了什么?
这样我有同样的问题:
<Router>
<Route path="/" component={App} />
<Route path="/example" component={Example}/>
</Router>
示例组件
import React from 'react';
class Example extends React.Component {
render(){
return <div>Example</div>
}
}
export default Example
这是 Link
:
<Link to={'/example'}>aa</Link>
控制台中没有错误。
更改后,我在控制台中收到此错误(由 Link
引起)
index.js(第 27585 行)警告:[react-router] 位置“/”不匹配任何路由
index.js(第 27585 行)警告:[react-router]
Router
不再将 history 属性默认为哈希历史。请改用hashHistory
单例。 https://github.com/ReactTraining/react-router/blob/master/upgrade-guides/v2.0.0.md#no-default-history原文由 Pablo 发布,翻译遵循 CC BY-SA 4.0 许可协议
您的示例路线嵌套在您的父路线中,因此您不需要
/
在/example
中。您也可以尝试设置一个
IndexRoute
无论您的主组件是什么,以便它具有参考。链接到路线可能会有所帮助,这样您就可以看到 URL 中出现的内容,以确保它是您要查找的内容。
你的 App 组件不应该渲染除
{this.props.children}
之外的任何东西,因为路由器正在处理的所有组件都将在这里渲染,路由器不只是渲染主文件中的东西,它控制路由和在 App 组件(通常称为 AppController)中安装哪些组件,因此您需要构建一个 Home 组件,该组件将在/
路由中呈现,并在您的路由器中声明使用IndexRoute
然后设置组件之间的链接,如果一切都正确完成,那么你就可以开始了。关联:
主要的:
应用程序控制器:
示例组件:
主页组件: