簡體   English   中英

replace: true 在 React router v6 中不會替換歷史記錄中的最后一個條目

[英]replace: true in React router v6 doesn't replace last entry in the history

以下代碼不會替換歷史堆棧中的最后一個條目:

// inside some component
const navigate = useNavigate()

// inside a hook or click handler
navigate('/someroute', {replace: true})
// ..

我已經檢查了文檔中的navigateFunction 接口,但無法判斷我做錯了什么。

https://stackoverflow.com/a/68694698/16407971 - 這個接受的答案不會替換我為演示設置的演示中歷史堆棧中的最后一項(在本地使用 CRA 但在 Codesandbox 中共享代碼)。 它只是不斷推送新的 URL 而不是替換上一個。 (創建了簡單count state 來為navigate生成新的 URL):

<button
  onClick={() => {
    navigate(`/another${count}`, { replace: true })
    setCount((prevCount) => prevCount + 1)
  }}
>

為什么這個沙盒代碼不起作用? (編輯:我錯誤地編輯了 Codesandbox 而不是在本地進行測試。在下面的代碼中它應該是{replace: true} 。即便如此,問題仍然存在。)

export default function App() {
  const navigate = useNavigate();
  const [count, setCount] = useState(0);
  return (
    <div className="App">
      <button
        onClick={() => {
          navigate(`/another${count}`, { options: { replace: true } });
          setCount((prev) => prev + 1);
        }}
      >
        CLICK ME {count}
      </button>
    </div>
  );
}

沙箱中的代碼不正確。 navigate function 采用第二個參數,選項 object。換句話說,而不是

navigate(`/another${count}`, { options: { replace: true } });

它應該是

navigate(`/another${count}`, { replace: true });

不過,您在問題的代碼片段中已經正確了。

需要明確的是,您的沙箱中的代碼實際上是將新條目推送到歷史記錄 state 中,因為沒有正確指定replace選項而不是 REPLACE。

export default function App() {
  const navigate = useNavigate();
  const [count, setCount] = useState(0);
  return (
    <div className="App">
      <button
        onClick={() => {
          navigate(
            `/another${count}`,
            { options: { replace: true } } // <-- not a REPLACE, but a PUSH
          );
          setCount((prev) => prev + 1);
        }}
      >
        CLICK ME {count}
      </button>
    </div>
  );
}

這是正常工作的完整代碼:

export default function App() {
  const navigate = useNavigate();
  const [count, setCount] = useState(0);
  return (
    <div className="App">
      <button
        onClick={() => {
          navigate(`/another${count}`, { replace: true }); // <-- REPLACE
          setCount((prev) => prev + 1);
        }}
      >
        CLICK ME {count}
      </button>
    </div>
  );
}

編輯 replace-true-in-react-router-v6-doesnt-replace-last-entry-in-the-history

暫無
暫無

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

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