简体   繁体   中英

React router v6 programmatically redirect

I am in /customerOrders/13 page and from there I try to redirect to /customerOrders/14 using navigate('/customerOrders/14') . Even though the URL is updated, page is not redirected to /customerOrders/14 .

Below are code fragments I extracted related to this from the codebase.

App.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}`);
    }
    ...
}

When you are on a given route:

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

and navigating to the same route already rendering the mounted component then the component needs to "listen" for changes to the route, in this case, specifically the id route match param that is updated. Use an useEffect hook with a dependency on the id route match param to rerun any logic depending on it.

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

  ...

};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM