简体   繁体   English

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

[英]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') .我在/customerOrders/13页面中,从那里我尝试使用navigate('/customerOrders/14')重定向到/customerOrders/14 Even though the URL is updated, page is not redirected to /customerOrders/14 .即使 URL 已更新,页面也不会重定向到/customerOrders/14

Below are code fragments I extracted related to this from the codebase.下面是我从代码库中提取的与此相关的代码片段。

App.js应用程序.js

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

CustomerOrderForm.jsx 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.并导航到已经渲染已安装组件的同一路由,然后组件需要“监听”路由的更改,在这种情况下,特别是更新的id路由匹配参数。 Use an useEffect hook with a dependency on the id route match param to rerun any logic depending on it.使用依赖于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