我正在使用 "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>
最佳答案
问题
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>
表单.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>
);
关于ReactJS:组件未在嵌套路由中呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66168586/