如何根据请求路由中的参数实现条件路由?

How do I achieve conditional routing based on the parameter in the requested route?

我正在开发一个类似 React js 博客的网站,我发现管理路由时遇到了一些问题。我的文章 URL 页面是这样的:website/pages/3

我想在页面索引为 1 时重定向到首页,因为首页默认是第一个有文章的页面。 我的路由器看起来像这样:

<Router>
        <Switch>
          <Route exact path="/" render={() => <Page postsPerPage={3}/>} />
          <Route exact path="/Page/:activePage" render={() => <Page postsPerPage={3}/>} />
          <Route path="/Login" component={Login} />
          <PrivateRoute path="/AddPost" component={AddPost}  />
          <Route path="/:postLocation" component={Post}  />
        </Switch>
      </Router>

如果 activePage 为 1,我想将“/Page/:activePage”路由到路由“/”呈现的组件。因此组件将是相同的 (Page),但路径将不同。

路由器中的条件渲染可以解决问题吗?如果可以,怎么做?我在考虑这些方面的事情:

 <Route exact path="/Page/:activePage" render={() => 
         {
            let {activePage} = useParams()
            if (activePage == 1) return (<Redirect to="/"/>)
            else return(<Page  postsPerPage={3}/>) 
          } 
          }/>

然而 React 似乎对我在那里使用 useParams 不满意(有一个编译错误:React Hook "useParams" cannot be called inside a callback。React Hooks must be called in a React function component or a custom React Hook 函数 react-hooks/rules-of-hooks)

我用常量值 1 而不是 activePage 参数测试了该代码段,它确实进行了重定向,所以基本上让我想到了如何从路径中检索参数的问题?

Component 的render 函数调用了三个参数,即match、history 和location。您可以使用它们来执行您尝试使用挂钩执行的操作。

<Route ... render={({match}) => {
 if (match.params.activePage == 1) {
  doYourStuff()
 }
}}

您可能应该在页面组件中处理路由,或者如果您愿意,可以创建一个单独的组件来处理条件路由。

例如:

function Pages (props) {

    const {activePage} = useParams()

    return activePage === 1 ? <Redirect to='/' /> : (
<div>
Your Pages component content here
</div>

)
}

export default Pages;

function ConditionalRoutingComponent(props) {

    const {activePage} = useParams()

    return activePage === 1 ? <Redirect to='/' /> : <Page  postsPerPage={3}/>
}

export default ConditionalRoutingComponent;

希望对您有所帮助

这种情况下的渲染函数渲染道具功能可以访问所有与组件渲染道具相同的路由道具(匹配、位置和历史)。 所以你基本上可以做类似的事情。

 <Route exact path="/Page/:activePage" render={(props) => 
         {
            if (props.match.params.activePage == 1) return (<Redirect to="/"/>)
            else return(<Page  postsPerPage={3}/>) 
          } 
      }
/>

看看你上面的例子,我宁愿不重定向任何东西,而是将逻辑带到页面组件中。在提取 activePage 参数的 componentDidMount 或 useEffect 函数中。我将检查它是否为 1(或您选择使用的任何标志值)然后我执行将由 home 组件执行的逻辑,否则我将正常处理路由。例如,如果您提取它并在它不是 1 的情况下提取到后端,那么当它为 1 时,您可以从函数中 return 并且它会像在主页上一样工作。或者,在检查之后,如果它是 1,则您可以重定向回 '/'。