【问题标题】:React JS (History.push)反应 JS (History.push)
【发布时间】:2021-04-26 17:23:56
【问题描述】:

我是新来的反应 如何路由到另一个组件,我使用了“History.push”方法 这是我的代码

import {useState} from 'react';
import axios from "axios"
import { toast } from 'react-toastify';
const api=axios.create({baseURL:"https://238.235/v1/user/signup"})
const useForm = (initialValues,validate) => {
    const [inputs,setInputs] = useState(initialValues);
    const [errors,setErrors] = useState({});

    const handleSubmit = (event) => {
        event.preventDefault();
        const validationErrors = validate(inputs);
        const noErrors = Object.keys(validationErrors).length === 0;
        setErrors(validationErrors);
        if(noErrors){
            console.log("Authenticated",inputs);
            api.post("/",inputs).then(response => {
                console.log(response.data.message);
              console.log(response);
                var message=response.data.message;
                 if (message==="Success") {
                  
                  toast.success(response.data.message +" : "+response.data.messageDescription);  
                  setTimeout(() => {
                    history.push("/auth/login");
                  }, 3000);
                }
                else
                {
                  toast.error(response.data.message +" : " +response.data.messageDescription);  
                }
              })
        }else{
            console.log("errors try again",validationErrors);
        }
        
    }

    const handleChange = (event) => {
        event.persist();
        setInputs(inputs => ({...inputs, [event.target.name]: event.target.value}));
    }

    return {
        handleSubmit,
        handleChange,
        inputs,
        errors
    };
}

我想做的是,如果消息成功,我想重定向到另一个组件,

我正在使用 history.push 方法。

提前致谢

【问题讨论】:

  • 你能分享一下你是如何在你的应用中渲染路由的,以及这个组件是如何访问history对象进行导航的吗?

标签: reactjs


【解决方案1】:

你可以使用 useHistory()

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

        function HomeButton() {
          let history = useHistory();

          function handleClick() {
            history.push("/home");
          }

          return (
            <button type="button" onClick={handleClick}>
              Go home
            </button>
          );
        }

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



        export default withRouter(useForm);

【讨论】:

    猜你喜欢
    • 2019-08-18
    • 2018-02-23
    • 1970-01-01
    • 1970-01-01
    • 2020-09-02
    • 2021-07-10
    • 2021-11-19
    • 2021-07-14
    • 2020-12-15
    相关资源
    最近更新 更多