代码之家  ›  专栏  ›  技术社区  ›  Jithesh Kt

如何处理react路由器dom(4.xx)中的空URL参数

  •  9
  • Jithesh Kt  · 技术社区  · 7 年前

    我的路线定义如下:

    <Route path='/result/:searchTerm' component={Result}/>
    

    它工作得很好。例如 localhost:3000/result/cat 页面工作。但是当用户决定删除 :searchTerm 从URL打开 localhost:3000/result/ 它显示空页。没有错误或任何东西。只是空白页。它甚至没有击中我的部件 {Result}

    所以我的疑问是如何处理这种情况。?假设我想重定向试图打开的用户 /result/ 没有 :searchTerms 到我的索引页。?怎么做。?

    3 回复  |  直到 7 年前
        1
  •  24
  •   Rich Churcher    7 年前

    我相信您可以为可选参数添加一个问号,因此:

    <Route path='/result/:searchTerm?' component={Result} />
    

    这是因为React路由器4使用 path-to-regexp 解释其路径属性。

    为了回答问题的最后一部分,您可以简单地测试 :searchTerm 如果未定义,则重定向用户。

        2
  •  2
  •   Shubham Khatri    6 年前

    如果您想在未添加参数的情况下将用户重定向到另一个页面,请执行以下操作

    <Switch>
       <Redirect from='/result/' to='/' exact />
       <Route path='/result/:searchTerm' component={Result}/>
    </Switch>
    

    但是,如果您希望显示相同的页面,那么也不需要参数,您可以只使用可选的路径参数。 查看此答案以了解更多详细信息: How to make path param to be optional in react router dom(v4)?

        3
  •  1
  •   Dane    7 年前

    Switch 是用于以独占方式渲染管线的组件。所以,一般来说,在结束的时候,孩子们在里面 转换 ,您可以为在其他路由中未明确指定的任何路径提供默认路由(在您的情况下为索引页)。

    如:

            <Switch>
              <Route exact path='/'
                component={()=>(<Redirect to='/index'/>)}/>
              <Route exact path='/index' component={Index}/>
              <Route path='/result/:searchTerm' component={Result}/>
              .
              .
              // default route, gets rendered if none of the above match:
              <Route component={NotFound404}/>
            </Switch>