【问题标题】:how to dynamic route in react如何在反应中动态路由
【发布时间】:2021-12-25 20:10:24
【问题描述】:

您好,我的动态路由器有问题 这是我的路由器代码

<Router>
    <Navbar />
    <Switch>
        <Route path={`/dashboard/buyList`} component={BuyList} />
        <Route path={`/dashboard/receipt`} component={WarehouseReceipt} />
        <Route path='/dashboard/new' component={NewBuy} exact/>
        <Route path='/dashboard/buyList:id' component={BuyInfo}/>
        <Route path='/dashboard' component={DashboardDetail} exact/>
        <Route component={NotFound} />
    </Switch>
</Router>

我的问题是我必须如何设置 buyList:id 并在我的项目中定义它?

【问题讨论】:

  • 您能否澄清您的问题以及问题所在?如果您只是询问如何链接到路径,只需渲染一个 Link 组件或使用 history.push 到“/dashboard/buyList123”或类似的。您确定您不是要在路由中添加路径分隔符,即path='/dashboard/buyList/:id' 而不是path='/dashboard/buyList:id'
  • 他询问嵌套路由
  • 感谢您的帮助,是的,我想要这样的路径 buyList:id 但我不知道如何反应才能理解产品的 id 并且必须显示它?
  • 您能与我们分享您在哪里链接到您的路线吗?如果您已正确设置路由和链接,Router 将使用更新后的 URL 重新呈现并呈现适当的路由。
  • @AshishKamble 链接可以来自路由上下文中的任何地方。在我们开始假设他们需要什么之前,我们如何等待 OP 说明问题并包含所有相关代码?

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


【解决方案1】:

这是一个小例子,它在嵌套路由中是如何工作的,

function BuyList () {
  return (
    <div>
      <h1>BuyList</h1>
      <ul>
        {buyList.map(({ name, id }) => (
          <li key={id}>
            <Link to={`/buylist/${id}`}>{name}</Link>
          </li>
        ))}
      </ul>

      <hr />

      <Route path={`/buylist/:id`}>
        <Buy />
      </Route>
    </div>
  )
}

带有反应钩子,

let { path, url } = useRouteMatch();

  <Switch>
    <Route exact path={path}>
      <h3>Please select a buy.</h3>
    </Route>
    <Route path={`${path}/:buyId`}>
      <Buy />
    </Route>
  </Switch>

购买是,

function Buy() {

  let { buyId } = useParams();

  return (
    <div>
      <h3>{buyId}</h3>
    </div>
  );
}

【讨论】:

    猜你喜欢
    • 2023-03-30
    • 1970-01-01
    • 2021-02-05
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    • 2021-09-21
    • 2016-12-28
    相关资源
    最近更新 更多