简体   繁体   中英

Redirect method not working in react-router-dom

I'm using react-router-dom . I need Redirect to dashboard when user registration is successful. but my Redirect component is not working. how can I fix this bug?

This is my Register.jsx file.

import React, { useState, useEffect } from "react";
import { Redirect } from "react-router-dom";
import Axios from "axios";

function Register() {
    // Use state
    const [name, setName] = useState();
    const [email, setEmail] = useState();
    const [password, setPassword] = useState();
    const [errors, setErrors] = useState({});

    // Form submitted
    const formSubmit = (e) => {
        e.preventDefault();
        // Send data
        Axios.defaults.withCredentials = true;
        Axios.get("http://localhost:8000/sanctum/csrf-cookie").then(
            (response) => {
                console.log(response);
                Axios.post("http://localhost:8000/api/auth/register", {
                    name: name,
                    email: email,
                    password: password,
                })
                    .then((res) => {
                        // Success full use registeration
                        if (res.status === 200) {
                            console.log("Success create Accound");
                            setErrors({});
                            <Redirect to="/dashboard" />;
                        }
                    })
                    .catch((err) => {
                        console.log("Attempt faild!");
                        console.log(err);

                        // Validation erros (422)
                        if (err.response) {
                            if (err.response.status === 422) {
                                if (
                                    Object.keys(err.response.data.errors)
                                        .length > 0
                                ) {
                                    setErrors(err.response.data.errors);
                                }
                            }
                        }
                    });
            },
        );
    };

}

export default Register;
react-router-dom version: ^5.2.0

Issue

You can't just try calling JSX like that, JSX needs to be rendered into the DOM.

Solution

Use the history object to issue an imperative redirect.

import { useHistory } from 'react-router-dom';

function Register() {
  const history = useHistory(); // <-- get history from hook

  // Use state
  ...

  // Form submitted
  const formSubmit = (e) => {
    e.preventDefault();
    // Send data
    Axios.defaults.withCredentials = true;
    Axios.get("http://localhost:8000/sanctum/csrf-cookie").then(
      (response) => {
        Axios.post("http://localhost:8000/api/auth/register", {
          name: name,
          email: email,
          password: password,
        })
          .then((res) => {
            // Success full use registeration
            if (res.status === 200) {
              console.log("Success create Accound");
              setErrors({});
              history.replace("/dashboard"); // <-- redirect
            }
          })
          .catch((err) => {
            ...
          });
        },
      );
  };
}

TL;DR

Use <Redirect/> when you're rendering a route. Use the useHistory() hook when you want to redirect programmatically.

Explanation

The line <Redirect to="/dashboard" /> creates a React Element, but that Element is never rendered, so React Router never executes the redirect.

<Redirect/> is meant to be used in a Function Component or the render() function of a Class Component, but here it is being used inside formSubmit() function.

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