簡體   English   中英

React 路由器 v6 以編程方式重定向

[英]React router v6 programmatically redirect

我在/customerOrders/13頁面中,從那里我嘗試使用navigate('/customerOrders/14')重定向到/customerOrders/14 即使 URL 已更新,頁面也不會重定向到/customerOrders/14

下面是我從代碼庫中提取的與此相關的代碼片段。

應用程序.js

import {
  BrowserRouter,
  Routes,
  Route
} from "react-router-dom";
...
<BrowserRouter>
    <Routes>
        <Route path="customerOrders/:id" element={<CustomerOrderForm />}></Route>
    </Routes>
<Router>

CustomerOrderForm.jsx

import { useNavigate  } from "react-router-dom";
...

const CustomerOrderForm = () => {
    let navigate = useNavigate();

    const save = async () => {
        //
        // logic to persist data goes here...
        //

        navigate(`/customerOrders/${customerOrderId}`);
    }
    ...
}

當您在給定路線上時:

<Route path="customerOrders/:id" element={<CustomerOrderForm />} />

並導航到已經渲染已安裝組件的同一路由,然后組件需要“監聽”路由的更改,在這種情況下,特別是更新的id路由匹配參數。 使用依賴於id路由匹配參數的useEffect掛鈎來重新運行依賴它的任何邏輯。

import { useNavigate, useParams } from "react-router-dom";

...

const CustomerOrderForm = () => {
  const navigate = useNavigate();
  const { id } = useParams();

  useEffect(() => {
    // rerun logic depending on id value
  }, [id]);

  const save = async () => {
    //
    // logic to persist data goes here...
    //

    navigate(`/customerOrders/${customerOrderId}`);
  };

  ...

};

暫無
暫無

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

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