我有这两个完全独立的组件。我想渲染App
当我输入 /
并渲染About
当我去 /#/about
我得到了这段代码(但我测试了很多其他代码):
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Link, browserHistory } from 'react-router'
import App from './App';
import About from './About';
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={App} >
<Route path="/about" component={About} />
</Route>
</Router>
, document.getElementById('root')
);
我也尝试过类似的方法
<Route path="/about" component={About} />
<Route path="/" component={App} />
并将/about 更改为 /#/about
, about
但它总是呈现“后备”/
,无论如何,它总是走这条路线。
我怎样才能让这个应用程序正确导航到 /
和/about
并渲染App
和 About
成分?
@编辑
假设我的“关于”组件已损坏,我删除了第一个 Route
并只保留/about
(仅保留/about
路线):
<Route path="/about" component={App} />
(我在之前的测试中也尝试保留“关于”)并更改了 /about
至about
和/#/about
.
我在控制台上收到此错误:
"VM3651 bundle.js:30801 Warning: [react-router] Location "/#/about" did not match any routes"
@编辑2
我按照 @Dominic 发布的示例进行了更改。我必须进行一些修改以确保两个组件都能渲染。我将 {this.props.children} 添加到所有组件以了解会发生什么。
//imports
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={About} >
<IndexRoute component={App} />
<Route path="/about" component={Other} />
</Route>
</Router>
,document.getElementById('root'));
路线http://localhost:3000/#/about
正在渲染:
> About > App
所以它正在渲染 IndexRoute,它没有被 /about
捕获。 .
这正是我现在所需要的,因为我不需要根组件,我想要 2 个通往 2 个不同且独立组件的路由。我需要两条兄弟路线之类的东西。
@编辑
About.js
import React, { Component } from 'react';
class About extends Component {
render() {
return (
<div>
About page
{this.props.children}
</div>
);
}
}
export default About;
解决方案:
由于我在 URL 中使用了 HASH (#),因此我应该使用 hashHistory
来自 <Router history={hashHistory}>
中的 React Router
最佳答案
您对路线的工作方式感到困惑 - About
是 App
路线的子级,因此为了呈现 About
,它具有渲染App
。
换句话说,您的 App
组件是“外壳”,其下的所有组件都在其内部渲染(通过 props.children
)。
您应该添加另一个路由来渲染/
。
import { ..., IndexRoute } from 'react-router'
<Route path="/" component={App} >
<IndexRoute component={Home} />
<Route path="about" component={About} />
</Route>
您的应用程序
不包含特定于路线的内容,它更像是这样的:
<div id="app">
<nav>app navigation</nav>
<main class="route-content">{props.children}</main>
</div>
关于javascript - 无法使 React-Router 渲染两个不同的组件,始终渲染 root,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40933688/