javascript 从react-router中排除路径< Router/>

1l5u6lss  于 2023-05-27  发布在  Java
关注(0)|答案(2)|浏览(212)

我正在尝试安装一个React路由器应用程序。我有/parties,所有派对的列表,然后我有/parties/:id,它给予了我一个派对的详细信息页面,还有/parties/create,我有一个创建派对的表单。
现在,我正试图让我的主资源总是在我的屏幕左侧,我的子资源总是在我的屏幕右侧。
我是这样设置的:

return <div>
      <div>
        <nav>
          <h1>Gamevote</h1>
          <AuthWidget authService={this.authService}/>
        </nav>
        <div class="content cnt" ref={this.content}>
          <this.PrivateRoute path="/" exact component={() => <Redirect to="/parties"/>} />
          <Route path="/register" exact component={() => <Register/>} />
          <Route path="/login" exact component={() => <Login authService={this.authService}/>} />
          <this.PrivateRoute path="/parties/:selectedParty?" component={this.AutowiredPartyList} />
        </div>
        <div class="big-content cnt" ref={this.bigContent}>
            <this.PrivateRoute path="/party/create" partyService={this.partyService} exact component={() => <this.AutowiredCreateParty/>}/>
            <this.PrivateRoute path="/parties/:party" exact component={PartyView}/>
         </div>
         <this.PrivateRoute path="/logout" exact component={this.Logout}/>
      </div>
    </div>
  }

但是现在当我转到/parties/create时,一个创建派对表单和一个带有id party的派对细节出现了。
有没有办法从匹配/parties/:id中排除/parties/create

smdncfj3

smdncfj31#

如果你想同时拥有/parties/create/parties/:id,请更改顺序:
path="/parties/create”(first)
path="/parties/:id”(last)
如果另一条路径带有/parties/:something?在它进入该路由之前存在。
这是因为"/parties/:id"匹配/parties/#####之后的任何内容。另外请注意,您必须添加Switch组件,以便每次只呈现一个路径。

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

function Index() {
  return <h2>Home</h2>;
}

function About() {
  return <h2>About create</h2>;
}

function AboutId() {
  return <h2>About with ID</h2>;
}

function Users() {
  return <h2>Users</h2>;
}

function AppRouter() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/users/">Users</Link>
            </li>
            <li>
              <Link to="/about/create">About</Link>
            </li>
            <li>
              <Link to="/about/1">About with id</Link>
            </li>
          </ul>
        </nav>
        <Switch>
          <Route path="/" exact component={Index} />
          <Route path="/users/" component={Users} />
          <Route path="/about/create" component={About} />
          <Route path="/about/:id" component={AboutId} />
        </Switch>
      </div>
    </Router>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<AppRouter />, rootElement);

https://codesandbox.io/s/withered-lake-o9kx4

carvr3hs

carvr3hs2#

排除路由的最佳方法是使用交换机和空路由作为要排除的路由。例如:如果你想隐藏按钮时,设置/用户路由被选中,你可以这样做:

<Switch>
  <Route path="/settings"/>
  <Route path="/:dashboard/:param">
    <Button />
  </Route>
</Switch>

相关问题