首页 > 解决方案 > 即使没有提供路径参数,也路由到相同的 React 组件

问题描述

即使没有提供路径参数,我也试图在我的应用程序中呈现相同的组件:

  <Switch>
    <Route
      path="/productInfoList/:product"
      component={ProductInfoList}
     />
  </Switch>

但是,如果 URL 中没有提供 ":product" 参数,则不会呈现组件。即使没有提供路径参数,有没有办法呈现相同的“ProductInfoList”组件?

我觉得必须有一种有效的方法来做到这一点,而不是path="/productInfoList"完全重新声明一条新路线。

标签: reactjsroutesreact-routerreact-router-dom

解决方案


您好,您可以选择没有婴儿车的路线,然后传入 history.push 或链接

history.push({
  pathname: '/template',
  search: '?query=abc',
  state: { detail: response.data }
})
<Link to={{
      pathname: '/template',
      search: '?query=abc',
      state: { detail: response.data }
    }}> My Link </Link>

正如你在这里看到的,如果你想获取数据,你可以传递一个状态,你可以像这样使用 props.location.state.detail 你可以跟踪你是否得到一个状态,然后按照你想要的方式使用它


推荐阅读