【问题标题】:Redirect method not working in react-router-dom重定向方法在 react-router-dom 中不起作用
【发布时间】:2021-07-24 22:08:19
【问题描述】:

我正在使用react-router-dom。用户注册成功后,我需要重定向到仪表板。但我的Redirect 组件不工作。如何修复此错误?

这是我的Register.jsx 文件。

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

【问题讨论】:

    标签: javascript reactjs redirect react-router-dom


    【解决方案1】:

    问题

    你不能只是尝试这样调用 JSX,JSX 需要渲染到 DOM 中。

    解决方案

    使用history 对象发出命令式重定向。

    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) => {
                ...
              });
            },
          );
      };
    }
    

    【讨论】:

    • 哇,非常感谢你!它现在工作得很好!
    • @Dinitharansidhu 如果此答案解决了您的问题,那么我邀请您将其标记为已接受的答案,如果您发现它有帮助/有用,那么不要忘记在可能的情况下也投票。干杯。
    【解决方案2】:

    TL;DR

    在渲染路线时使用&lt;Redirect/&gt;。 当您想以编程方式重定向时,请使用 useHistory() 挂钩。

    说明

    &lt;Redirect to="/dashboard" /&gt; 行创建了一个 React 元素,但该元素永远不会被渲染,所以 React 路由器永远不会执行重定向。

    &lt;Redirect/&gt; 用于函数组件或类组件的render() 函数,但这里是在formSubmit() 函数内部使用。

    【讨论】:

      猜你喜欢
      • 2021-07-27
      • 2021-02-11
      • 2018-05-21
      • 1970-01-01
      • 2020-04-23
      • 2017-10-05
      • 2018-02-04
      • 1970-01-01
      • 2018-07-31
      相关资源
      最近更新 更多