簡體   English   中英

無法在反應中重定向到主頁

[英]No able to redirect to home page in react

當用戶單擊EDIT圖標時,將打開一個頁面。 用戶submit記錄后,如果成功,我們的頁面應該重定向到ListCertificate

當用戶單擊編輯按鈕時,下面的行將運行。 並打開編輯表格。

<Link to={`/${props.certificate.id}/edit` }>Edit</Link>

用戶成功保存后,我們的頁面應該重定向到ListCertificate組件。

所以我在寫

 .then(function (response: any) {
      console.log(response);
      toast("🦄 Record updated successflly", {
        position: "top-right",
        autoClose: 2000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined
      });
       return <Redirect  to='/listcertificate'  />
    })

這條線不工作。

return <Redirect  to='/listcertificate'  />

在 app.js 中,我使用下面的方法調用了 ListCertificate。

<Route  path ="/listcertificate" component={Listcertificate} ></Route>

localhost:4200/listcertificate工作正常。 但它也沒有從editcomponent重定向到同一頁面。

不在JSX中時使用useHistory而不是Redirect

import {useHistory} from "react-router-dom"

const history = useHistory();
history.push('/listcertificate');

如果您使用的是react-router-dom版本 6,則可以使用useNavigate

 import {useNavigate} from "react-router-dom";
 
 const navigate = useNavigate();
 
 navigate("/listcertificate", { replace: true });

使用react-router-dom v6,您可以使用useNavigate掛鈎以編程方式進行導航。 文檔

import { useNavigate } from "react-router-dom";
..
const navigate = useNavigate();
...
.then(function (response: any) {
      console.log(response);
      toast("🦄 Record updated successflly", {
        position: "top-right",
        autoClose: 2000,
        hideProgressBar: false,
        closeOnClick: true,
        pauseOnHover: true,
        draggable: true,
        progress: undefined
      });
       navigate("/listcertificate", { replace: true });
    })

您忘記在<Navigate/>中添加replace道具。

<Navigate replace>屬性告訴路由器在更新 URL 時使用history.replaceState() ,這樣 / 條目就不會出現在歷史堆棧中。 這意味着當有人點擊后退按鈕時,他們最終會回到他們導航到/ 閱讀更多之前所在的頁面

改變這個

<Redirect to='/listcertificate' />

對此

<Redirect to='/listcertificate' replace />

或對此

<Redirect to='/listcertificate' replace={true} />

暫無
暫無

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

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