簡體   English   中英

React Router Dom 5.1.2 — 選項卡支持

[英]React Router Dom 5.1.2 — Tabs support

我是 react-router-dom 的新手,我正在嘗試創建一個選項卡菜單,每個選項卡都有不同的路線。 我試圖通過保持隱藏的選項卡安裝,使選項卡 state 在選項卡切換之間保持持久。 我怎樣才能做到這一點? 每次路由切換時,React 路由器都會重新掛載每個組件,即使根據文檔使用渲染道具也是如此。

我的聯系人組件有一個內部 state,當我導航到另一個選項卡時,它已卸載,因此 state 丟失了

      <Route path={`${path}`} exact render={() => <Home />} />
      <Route path={`${path}/profile`} render={() => <Profile />} />
      <Route path={`${path}/contact`} render={() => <Contact />} />

這是示例的代碼框: https://codesandbox.io/s/gallant-lake-vhdby?file=/src/App.js

您可以在卸載時在 localStorage 中維護 state 並在 initialState 中重新填充它

const Contact = () => {
  const [count, setCount] = useState(JSON.parse(localStorage.getItem("count")));

  useEffect(() => {
    return () => {
      console.log("unmounted");
    };
  });

  useEffect(() => {
    console.log("mounted");
    return () => {
      localStorage.setItem("count", count);
    };
  }, [count]);
  return (
    <div onClick={() => setCount(prevCount => prevCount + 1)}>
      You're on the Contact Tab. You pressed me {count} times
    </div>
  );
};

另一種解決方案是不在聯系組件中維護 state 而是在 App 組件中,並將其作為道具傳遞給 Contact

<Route path={`${path}/contact`} render={(routerProps) => <Contact {...routeProps} count={count} setCount={setCount}/>} />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM