React router v6 中的replace: true 不会替换历史记录中的最后一个条目

问题描述 投票:0回答:2

以下代码不会替换历史堆栈中的最后一个条目:

// 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,而不是替换上一个 URL。 (创建了简单的

count
状态来为
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>
  );
}
javascript reactjs react-router react-router-dom
2个回答
0
投票

沙盒中的代码不正确。

navigate
函数采用第二个参数,即 选项对象。换句话说,而不是

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

应该是

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

不过,您问题中的代码片段中的内容是正确的。

需要明确的是,沙箱中的代码实际上是将新条目推送到历史状态中,因为未正确指定

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>
  );
}

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


0
投票

可以找到解决方案吗,因为我面临着同样的问题,这真的很令人畏惧

© www.soinside.com 2019 - 2024. All rights reserved.