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

时间:2017-12-06 06:26:18

标签: reactjs react-router-v4 react-router-dom

我的路线定义如下:

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

工作正常。例如,localhost:3000/result/cat页面有效。但是,当用户决定从网址中删除:searchTerm并仅打开localhost:3000/result/时,它会显示空白页面。没有错误或任何东西。只是空页。它甚至没有击中我的组件{Result}

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

3 个答案:

答案 0 :(得分:9)

我相信你可以为可选参数添加一个问号,所以:

Hindi.islu

这是有效的,因为React Router 4使用path-to-regexp来解释其路径属性。

要回答问题的最后部分,您只需测试<Route path='/result/:searchTerm?' component={Result} /> 的值,如果未定义,则重定向用户。

答案 1 :(得分:2)

如果您想在未添加参数的情况下将用户重定向到其他页面,则可以执行以下操作

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

但是如果你想显示相同的页面,那么没有params,你可以使用可选的路径参数。  请查看此答案以获取更多详细信息:How to make path param to be optional in react router dom(v4)?

答案 2 :(得分:1)

Switch是用于专门呈现路径的组件。因此,通常,在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>
相关问题