![](/img/trans.png)
[英]how to keep React components mounted phase while switching between defrent components
[英]React Router Tabs — Keep Components Mounted
我必須做更多的挖掘以確認這確實有效,但是通過閱讀 React Router 文檔,我發現了有關Route
組件的內容。 每次路由更改時,使用component
道具都會重新安裝組件。 但是使用其他渲染方法,您可能能夠實現您想要的。 我會使用render
,但children
也可以工作嗎?
這是 react-router-dom-v5 doc 在<Route/>
render
、 children
和component
prop 上推薦的路由方法。 這樣我們的組件就會在每次路徑匹配時重新初始化和重新安裝。
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/contact">
<Contact />
Route>
<Route path="/about">
<About />
</Route>
</Switch>
由於您(Kat)希望通過安裝隱藏的選項卡來保持選項卡轉換之間的選項卡狀態。
react-router-dom
的pathname
在選項卡之間切換來實現此目的。const { pathname } = useLocation();
{pathname === "/"? <Home/>: null}
{pathname === "/contact"? <Contact/>: null}
{pathname === "/about"? <About/>: null}
CSS
的第二個解決方案演示: https : //codesandbox.io/s/react-router-moud-routes-32dxf? file =/ src / App.js
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.