React with Typescript window 移动到主页但它重新启动数据

React with Typescript window move to homePage but it restart the data

我正在尝试将此组件重定向到 HomePage,但在它被重定向到主页后,它会重新启动其中的数据。

有什么替换 window.location.href = "/HomePage" 的建议吗?

import React, { useEffect } from "react";

const Thankyou = () => {

    useEffect(() => {
        setTimeout(() => {
            window.location.href = "/HomePage"
        }, 10000)
    }, [])

    return (
        <div className={"movie-container"}>
            <h2>
                Thank you for ordering...<br/>
            </h2>
            <h2>Page will redirect in 10 seconds...</h2>
        </div>
    )
}

export default Thankyou;

这些是App.tsx

的路线
const App: FC = () => {
    return (
        <>
            <Header/>
            <Routes>
                <Route path="/" element={<Navigate replace to='/HomePage' />} />
                <Route path="/HomePage" element={<HomePage />} />
                <Route path="/FavoritePage" element={<FavoritePage />} />
                <Route path="/MoviePage/movie/:id" element={<MoviePage />} />
                <Route path="/Thankyou" element={<Thankyou />} />
            </Routes>
        </>
    )
};

这是index.tsx

ReactDOM.render(
    <React.StrictMode>
        <BrowserRouter>
            <GalleryProvider>
                <App />
            </GalleryProvider>
        </BrowserRouter>
    </React.StrictMode>,
    document.getElementById('root')
);

当您改变 window.location.href 时,您最终会重新加载应用程序。这有效地重新安装了整个应用程序,因此任何 React 状态都将被重置。

使用 navigate 函数发出命令式重定向。

import React, { useEffect } from "react";
import { useNavigate } from 'react-router-dom';

const Thankyou = () => {
  const navigate = useNavigate();

  useEffect(() => {
    const timer = setTimeout(() => {
      navigate("/HomePage", { replace: true });
    }, 10000);

    return () => {
      clearTimeout(timer); // <-- clear timeout effect on unmount
    };
  }, [])

  return (
    <div className="movie-container">
      <h2>Thank you for ordering...</h2>
      <h2>Page will redirect in 10 seconds...</h2>
    </div>
  );
};

export default Thankyou;