【发布时间】:2019-01-16 03:28:35
【问题描述】:
我在玩react-router,在使用嵌套路由时遇到问题。
这是我的父路由器:
<Router>
<div>
<Route exact path="/" component={HomePage} />
<Route path="/account" component={AccountDashboard} />
</div>
</Router>
这是AccountDashboard里面的路由器:
<Router>
<Route path="/account/password-reset" component={ChangePassword} />
<Route path="/account/sign-out" component={SignOut} />
</Router>
一旦导航到/account/password-reset 或/account/sign-out,我似乎无法导航回父路由器的根目录(以查看HomePage 组件)。子路由器只是返回 null。
例如,我尝试在 ChangePassword 组件中同时调用 props.history.push('/') 和 props.history.reset('/'),但子路由器返回 null。
如果我在 AccountDashboard 路由器中添加 '/' 的路由,我提供的任何组件都可以正常渲染,因为 AccountDashboard 中的路由器与之匹配,但我想重定向到 ChangePassword 组件中的 '/' 并显示 @ 987654334@ 组件通过父路由器。
如何在子/嵌套路由器中导航到父路由器上的路由?
编辑:我刚刚从头开始做了一个基本的实现,同样的问题:
import React, { Component } from 'react';
import './App.css';
import { BrowserRouter as Router, Route, Link, withRouter } from "react-router-dom";
const Blue = withRouter(({ history }) => (
<div style={{ border: "1px solid #222", width: "300px", padding: "4px", margin: "4px"}}>
<h2>Blue Component</h2>
<span
style={{color: 'blue', textDecoration: 'underline'}}
onClick={() => { history.replace('/') }}>
Go back to Letters
</span>
</div>
));
const Green = withRouter(({ history }) => (
<div style={{ border: "1px solid #222", width: "300px", padding: "4px", margin: "4px"}}>
<h2>Green Component</h2>
<span
style={{color: 'blue', textDecoration: 'underline'}}
onClick={() => { history.replace('/') }}>
Go back to Letters
</span>
</div>
));
const Letters = () => (
<div style={{ border: "1px solid #222", width: "300px", padding: "4px", margin: "4px"}}>
<h2>Letters (Root) Component</h2>
</div>
)
const Colors = () => (
<Router>
<div>
Child Router
<br></br>
[ <Link to="/colors/blue">Blue</Link> ]
[ <Link to="/colors/green">Green</Link> ]
<Route path="/colors/blue" exact component={Blue} />
<Route path="/colors/green" component={Green} />
</div>
</Router>
);
class App extends Component {
render() {
return (
<Router>
<div>
Parent Router
<br></br>
[ <Link to="/">Letters</Link> ][ <Link to="/colors">Colors</Link> ]
<Route path="/" exact component={Letters} />
<Route path="/colors" component={Colors} />
</div>
</Router>
);
}
}
export default App;
使用上面的代码,应用程序将加载并显示Letters 组件。如果您单击Colors,您将被带到第二个路由器,您可以在其中选择“蓝色”或“绿色”,每个路由器都有一个返回“/”的链接。当您点击该链接时,URL 会正确更改为“/”,但不会显示原始的 Letters 组件。
【问题讨论】:
-
你是说当你从一个子组件按下后退按钮时,它不是返回到上一页吗?或者子组件中的
<Link>到“/”也不起作用? -
在您的应用程序中使用两个路由器有什么理由吗?顶层应该只有一个路由器。这个沙盒做你想做的事吗:codesandbox.io/s/8kwy5pkvm8?
-
你完全正确。我不应该有两个路由器。一旦我从其他子路线周围删除了额外的
Router标签,一切都像一个魅力。如果您可以将其发布为答案,我将很乐意接受。谢谢!
标签: javascript reactjs react-router