首頁  >  問答  >  主體

透過自己點擊連結來重新渲染React Router元件。

<p>我用 <code>react-router-dom</code> v6</p> <h1>代碼</h1> <pre class="brush:php;toolbar:false;"><NavLink to="/pathOne" className="ripple">label1</NavLink> <NavLink to="/pathTwo" className="ripple">label2</NavLink></pre> <h1>問題</h1> <p>當你點擊一個連結或另一個連結時,Route元件會如預期進行渲染。但是,如果"/pathOne"處於活動狀態並且我再次點擊它,則什麼都不會發生。 </p><p>是否有一種方法可以透過點擊活動連結來強制重新渲染路由元素? </p><p>如果設定了reloadDocument屬性,我可以刷新整個頁面,但這不是一個可行的選項。 </p><p><code></code></p>
P粉295728625P粉295728625472 天前483

全部回覆(1)我來回復

  • P粉432906880

    P粉4329068802023-07-28 12:05:00

    If all you really want is for the route component to rerender each time the link to its route is clicked then just have those components call the useLocation hook. Each time the link is clicked a new location object reference is created. The new location object reference is enough to trigger the component using it to be rerendered.

    Example:

    const PathOne = () => {
      useLocation();
    
      useEffect(() => {
        console.log("PathOne rerender");
      });
    
      return <h1>PathOne</h1>;
    };
    
    const PathTwo = () => {
      useEffect(() => {
        console.log("PathTwo rerender");
      });
    
      return <h1>PathTwo</h1>;
    };
    function App() {
      return (
        <div className="App">
          <NavLink to="/pathOne" className="ripple">
            label1
          </NavLink>
          <NavLink to="/pathTwo" className="ripple">
            label2
          </NavLink>
          <Routes>
            <Route path="/pathOne" element={<PathOne />} />
            <Route path="/pathTwo" element={<PathTwo />} />
          </Routes>
        </div>
      );
    }

    回覆
    0
  • 取消回覆