繁体   English   中英

使用 react-router 在应用程序中使用 react-router 反应组件

[英]React component with react-router inside an app with react-router

我正在开发一个带有自己的 react-router-dom 的反应组件,以便能够处理/post/post/123之类的路径。

我需要将 package 这个组件作为 npm 模块,以便它可以嵌入到另一个具有自己的 react-router-dom 的 React 应用程序中。

托管应用程序:

<Router>
  <Switch>
    <Route path="/posts" exact={true}>
      <Blog />
    </Route>
  </Switch>
</Router

在博客组件中:

<Router basename="/posts">
   <Switch>
     <Route path="/">
       <p>Display all posts</p>
     </Route>
     <Route path="/post/:id">
       <p>Display details for post with id</p>
     </Route>
   </Switch>
</Router>

当我访问/posts路径时,我收到Display all posts消息。 但是,当我访问/post/123路径时,我看不到Display details for post with id信息。

如何让内部路由器路径与外部路由器一起使用?

您缺少确切的关键字

 <Router basename="/posts">
       <Switch>
         <Route exact path="/">
           <p>Display all posts</p>
         </Route>
         <Route exact path="/post/:id">
           <p>Display details for post with id</p>
         </Route>
       </Switch>
    </Router>

对于遇到此问题的任何人 - 我通过将history传递给两个路由器来解决它:

主应用程序:

import { BrowserRouter as Router, Route } from 'react-router-dom';

const App = () => {
  return (
    <Router>
      <Switch>
        <Route path="/posts">
          <Blog />
        </Route>
      </Switch>
    </Router>
  );
}

博客组件:

import { BrowserRouter as Router, Route } from 'react-router-dom';

const Blog = () => {
  return (
    <Router basename="/posts">
      <Switch>
        <Route path="/" exact>
          <p>Display all posts</p>
        </Route>
        <Route path="/post/:id" exact>
          <p>Display details for post with id</p>
        </Route>
      </Switch>
    </Router>
  )
}

这是完整的解决方案:尝试这样做:

如果您在“路由器”中使用基本名称,请这样做

const BlogPage = () =>{
    return(
        <Router basename='/posts'>
            <Switch>
                <Route path='/posts' exact>
                    <p>Display All Posts </p>
                </Route>
                <Route path='/:id' exact>
                    <p>Display Post with Id </p>
                </Route>
            </Switch>
        </Router>
    )
}

或者,如果您在不使用 basename 的情况下使用 Router,那么它应该是这样的:

const BlogPage = () =>{
    return(
        <Router>
            <Switch>
                <Route path='/posts' exact>
                    <p>Display All Posts </p>
                </Route>
                <Route path='/posts/:id/' exact>
                    <p>Display Post with Id </p>
                </Route>
            </Switch>
        </Router>
    )
}

查看它们之间的区别

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM