【问题标题】:ReactJS: Component is not rendering in Nested RoutingReactJS:组件未在嵌套路由中呈现
【发布时间】:2021-05-16 00:16:36
【问题描述】:

我正在使用"react-scripts": "4.0.2",我所有的组件都是 React Hooks。我的逻辑涉及嵌套路由,但未呈现最终结果。

Body.js:

<Switch>
    <Route path="/form" exact component={Forms}></Route>
    <Route path="/" exact component={ShopCards}></Route>
</Switch>

Forms.js:

const expandFormHandler = (pid) => {
console.log("PID:" + pid);           //It is printing correcly
props.history.push({ pathname: "/form/" + pid });  //URL is also changing accordingly
}

return (
<div>
  {prodCards.map((card, index) => (
    <ProductCard
      key={index}
      expand={expandFormHandler.bind(this, card.pid)}
    />
  ))}

  <Route path={props.match.url + "/:id"} exact component={Modal} />
//<Route path="/form/:id" exact component={Modal} />   //Tried this too
</div>
  );

Modal.js:

<h1>{props.match.params.id}Hello</h1>

即使 useEffect() 未执行,模态也未呈现。

现在,如果我将 Modals Route 放在 Body.js 中,就像跟随 Modal 一样呈现但不在 ProductCard 下方的同一页面中

<Switch>
    <Route path="/form" exact component={Forms}></Route>
    <Route path="/form/:id" exact component={Modal} />
    <Route path="/" exact component={ShopCards}></Route>
</Switch>

【问题讨论】:

  • 您能说明一下您的目标是什么吗?如果 url 包含 :id,您想在同一页面上显示 Modal 组件和 Forms 组件?
  • 如果您希望在与 ProductCard 相同的页面上显示模态。我不认为使用这样的路线可以实现它。

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


【解决方案1】:

问题

Route 渲染 Forms 使用的是完全匹配,即当路径为完全“/form”时

<Switch>
  <Route path="/form" exact component={Forms}></Route> // <-- exact match!!
  <Route path="/" exact component={ShopCards}></Route>
</Switch>

当路径是任何子路由时,即“/form/3”,它不再是完全匹配并且Form 不再呈现。

解决方案

从根路由中移除 exact 属性。

<Switch>
  <Route path="/form" component={Forms}></Route> // <-- general match
  <Route path="/" exact component={ShopCards}></Route>
</Switch>

Forms.js

return (
  <div>
    {prodCards.map((card, index) => (
      <ProductCard
        key={index}
        expand={expandFormHandler.bind(this, card.pid)}
      />
    ))}

    <Route path="/form/:id" component={Modal} /> // <-- more specific match
  </div>
);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-19
    • 2023-04-07
    • 1970-01-01
    • 2013-11-04
    • 1970-01-01
    • 2019-04-15
    • 1970-01-01
    相关资源
    最近更新 更多