使用React Router 4的嵌套交换机和默认子路由

时间:2018-11-27 13:59:01

标签: reactjs react-router-v4

尝试导航到Warning: You tried to redirect to the same route you're currently on时,我不断收到警告/articles/<article_id>/details

我目前有以下路线:

  • /
  • /settings
  • /settings/connections
  • /articles
  • /articles/:article_id
  • /articles/:article_id/:author_id
  • /articles/:article_id/:author_id/details
  • /login
  • /logout

这是我的主要Switch的样子:

<Router>
  <Switch>
    <Route path="/articles" component={Articles} />
    <Route path="/settings" component={Settings} />
    <Route path="/login" component={Login} />
    <Route path="/logout" component={Logout} />
    <Redirect from="/" to="/articles" exact />
    <Route component={NotFound} />
  </Switch>
</Router>

然后在Articles.js中,我还有一个Switch

<Switch>
  <Route path="/articles/:article_id/details" component={ArticleDetail} />
  <Route path="/articles/:article_id/authors" component={ArticleAuthors} />
  <Route path="/articles/:article_id/authors/:author_id" component={ArticleAuthor} />
  <Route path="/articles/:article_id/authors/:author_id/details" component={ArticleAuthorDetails} />
  <Redirect from="/articles/:article_id" to="/articles/:article_id/details" exact />
</Switch>

这是问题所在: 当我手动导航到/articles/<article_id>/details时,会收到上述警告。我尝试在重定向之前手动检查当前路由是在/articles/<article_id>还是/articles/<article_id>/上,但这似乎是错误的/错误的。

是否有更简单的方法来实现我要完成的任务?还是我滥用反应路由器?

1 个答案:

答案 0 :(得分:0)

您能做到这一点吗? 如果您可以提供更多代码(或存储库),我可以看看。

我尝试了以下对我有用的软件(react-router-dom版本4.3.1)

import React from "react";
import { BrowserRouter as Router, Route, Switch, Redirect } from "react-router-dom";

const Settings = () => (<div>Settings</div>);
const ArticleAuthors = () => (<div>ArticleAuthors</div>);
const ArticleDetail = () => (<div>ArticleDetail</div>);

const Articles = () => (
    <div>
        Articles
        <Switch>
            <Route path="/articles/:article_id/details" component={ArticleDetail} />
            <Route path="/articles/:article_id/authors" component={ArticleAuthors} />
            <Redirect from="/articles/:article_id" to="/articles/:article_id/details" exact />
        </Switch>
    </div>
);


const App = () => (
    <Router>
        <Switch>
            <Route path="/articles" component={Articles} />
            <Route path="/settings" component={Settings} />
            <Redirect from="/" to="/articles" exact />
        </Switch>
    </Router>
);

export default App;