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

How to handle empty URL parameter in react router dom (4.xx)

我的路线定义如下:

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

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

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

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

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

这是可行的,因为 React Router 4 使用 path-to-regexp 来解释它的路径 属性。

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

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

<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)?

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>