在 React 中使用 exact 组件的多路由

Multi-routes to component with exact in React

我有一个组件应该在您第一次加载网页时显示,但也会在特定路径上显示。

所以,我有用户组件,这个应该在两种情况下显示:“/”或“/users”。

目前我是这样做的:

<Switch>
    <Route path="/" exact component={Users} />
    <Route path="/users" exact component={Users} />
</Switch>

Switch中还有其他路由,但没必要复制。 我知道可以进行多路由:

<Route path={"/" | "/users"} component={Users} />

但是这不起作用,因为我不能使用 exact。我怎样才能通过这种方式实现它?

好的,我试了一下,找到了解决办法。


const [x, setX] = useState(false)

<Route path={x ? "/profile" : "/other"} component={Users} />

然后,如果您点击 link,您应该会进入 /profile 添加 onClick={() => setX(true)} 如果 /other 添加到 onClick={() => setX(false)}

您需要使用重定向

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

结果:

<Switch>
 <Route path="/users" component={Users} />

 <Route exact path="/">
  <Redirect to="/users" />
 </Route>
</Switch>