我正在使用 "react-scripts": "4.0.2"
并且我的所有组件都是 React Hook。我的逻辑涉及嵌套路由,但未呈现最终结果。
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>
答案 0 :(得分:3)
Route
渲染 Forms
使用完全匹配,即当路径是 exactly "/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>
);