admin管理员组

文章数量:1278919

In older React Router Dom versions, I was able to use this code to redirect if a user is logged in:

history.push('/login?redirect=shipping')

Now in v6, I am using the useNavigate functions instead of history.push, but it's not working as it is taking me to /login/shipping instead of /shipping. Currently, this is my navigate code:

let navigateCart = useNavigate() 
// some code here
navigateCart('/login?redirect=shipping') // the mistake is inside the parenthesis here but I don't know what it is!

This is my router config:

<BrowserRouter>
  <Container>
    <Routes>
      <Route path="/" element={<HomeScreen />} exact />
      <Route path="/login" element={<LoginScreen />} />
      <Route path="/profile" element={<ProfileScreen />} />
      <Route path="/shipping" element={<ShippingScreen />} />
    </Routes>
  </Container>
</BrowserRouter>

Login Screen Function :

function LoginScreen() {

    let navigateLog = useNavigate()
    let location = useLocation()

    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')

    const dispatch = useDispatch()

    const redirect = location.search ? location.search.split('=')[1] : '/'
    

    const userLogin = useSelector(state => state.userLogin)
    const { error, loading, userInfo } = userLogin


    useEffect(() => {
        if (userInfo) {
            navigateLog(redirect)
        }
    }, [navigateLog, userInfo, redirect])

    const submitHandler = (e) => {
        e.preventDefault()
        dispatch(login(email, password))
    }

In older React Router Dom versions, I was able to use this code to redirect if a user is logged in:

history.push('/login?redirect=shipping')

Now in v6, I am using the useNavigate functions instead of history.push, but it's not working as it is taking me to /login/shipping instead of /shipping. Currently, this is my navigate code:

let navigateCart = useNavigate() 
// some code here
navigateCart('/login?redirect=shipping') // the mistake is inside the parenthesis here but I don't know what it is!

This is my router config:

<BrowserRouter>
  <Container>
    <Routes>
      <Route path="/" element={<HomeScreen />} exact />
      <Route path="/login" element={<LoginScreen />} />
      <Route path="/profile" element={<ProfileScreen />} />
      <Route path="/shipping" element={<ShippingScreen />} />
    </Routes>
  </Container>
</BrowserRouter>

Login Screen Function :

function LoginScreen() {

    let navigateLog = useNavigate()
    let location = useLocation()

    const [email, setEmail] = useState('')
    const [password, setPassword] = useState('')

    const dispatch = useDispatch()

    const redirect = location.search ? location.search.split('=')[1] : '/'
    

    const userLogin = useSelector(state => state.userLogin)
    const { error, loading, userInfo } = userLogin


    useEffect(() => {
        if (userInfo) {
            navigateLog(redirect)
        }
    }, [navigateLog, userInfo, redirect])

    const submitHandler = (e) => {
        e.preventDefault()
        dispatch(login(email, password))
    }
Share Improve this question edited Apr 9, 2023 at 5:09 Youssouf Oumar 46.2k16 gold badges101 silver badges104 bronze badges asked Aug 5, 2022 at 10:41 bysEcodebysEcode 1373 silver badges10 bronze badges 10
  • Show your router configuration – Konrad Commented Aug 5, 2022 at 11:06
  • @KonradLinkowski Ok Done! It is working for other routes though ! – bysEcode Commented Aug 5, 2022 at 11:09
  • @KonradLinkowski If you need more code let me know please – bysEcode Commented Aug 5, 2022 at 11:10
  • @bysEcode you declared navigate and then using navigateCart, is that normal? – Youssouf Oumar Commented Aug 5, 2022 at 11:11
  • 2 You are getting the parameter here redirect=shipping inside LoginScreen ponent and making the redirection I assume, if so can you past the code for LoginScreen? – Youssouf Oumar Commented Aug 5, 2022 at 11:23
 |  Show 5 more ments

2 Answers 2

Reset to default 8

Change that navigateLog(redirect) line inside the useEffect in LoginScreen to this one:

navigateLog(`/${redirect}`);

In your case, it's redirecting to /login/shipping instead of /shipping, cause it's like you are calling navigateLog("shipping"), and without / in front, it's used as a relative path. This means it takes into account your current path, which in your case happens to be /login.

Issue

The redirect target path is "shipping" instead of "/shipping". In react-router-dom@6 there are relative paths and absolute paths. The difference is simple, absolute paths start with a leading "/" character while relative paths do not. navigate("shipping") will append "shipping" to the end of the current pathname and navigate there.

Solution

Either prepend the leading "/" when navigating:

navigate(`/${navigateLog}`, { replace: true });

Or include it when you initially navigate:

navigateCart('/login?redirect=/shipping');

You'll likely also want to use the useSearchParams hook to access the redirect query parameter instead of relying on it to be at a specific string position.

function LoginScreen() {
  const navigateLog = useNavigate();
  const [searchParams] = useSearchParams();

  ...

  const redirect = searchParams.get("redirect") || '/';
    
  ...

  useEffect(() => {
    if (userInfo) {
      navigateLog(redirect, { redirect: true });
    }
  }, [navigateLog, userInfo, redirect])

  ...

Note that in issuing the imperative redirect that I've included an options object to the navigate function that specifies replace: true, this is to issue a REPLACE action instead of a PUSH action.

本文标签: javascriptReact Router DomuseNavigate not redirecting to the right url pathStack Overflow