What is the difference between Navigate
component and navigate
from useNavigate()
hook?.
if (therapy !== desiredGroupTherapy || required.includes('admin') && !isAdmin) {
const pathname = generatePath(pageRoutes.DASHBOARD, {
groupId: desiredGroupId,
therapy: therapyForValidGroup,
})
navigate(pathname, { replace: true })
// return <Navigate to={pathname} replace />
}
I have issue with navigate
here. How that should work: I redirect to that page, but at first time I have no therapy
, so I should redirect to the same page but my therapy
now will be equal to therapyForValidGroup
. I have custom hook useTherapy()
which takes therapy
from URL. So at first time when it is undefined it crashes using navigate
function. But using Navigate
component, it works fine. So what is the difference?
The navigate
function, when invoked, is a side-effect. The code is calling navigate
directly in the body of the component as an unintentional side-effect.
Move the logic into a useEffect
hook.
Example:
import React, { useEffect } from "react";
import { generatePath, useParams } from "react-router";
import { useNavigate } from "react-router-dom";
import { usePathPattern } from "./usePathPattern";
export const Authorization = ({ children }) => {
const params = useParams();
const navigate = useNavigate();
const userTherapy = params.therapy;
const name = params.name;
const pattern = usePathPattern();
useEffect(() => {
if (userTherapy === "undefined" && name) {
const pathname = generatePath(pattern, {
name,
therapy: "TEST"
});
navigate(pathname, { replace: true });
}
}, [name, navigate, pattern, userTherapy]);
return children;
};
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.