【问题标题】:Using Redirect upon form submission in React在 React 中提交表单时使用重定向
【发布时间】:2019-11-05 15:01:37
【问题描述】:

我一直在尝试在用户登录时重定向。登录名可以在我的数据库中正常工作,并将有条件地为我的管理门户呈现我的新链接。我在获得状态码 200 时尝试使用重定向,但我不确定这是否是正确的方法。

登录组件的 axios 帖子:

const handleSubmit = e => {
    e.preventDefault();
    console.log(adminLogin)

    axios
      .post("/api/Authentication", adminLogin)
      .then(function(response) {
        if (response.status === 200) {
          setIsLoggedIn(true);
          <Redirect to="/inventory" />
        }
        setAdminLogin(response.data);
        console.log(response);
      })
      .catch(function(error) {
        console.log(error);
      });

【问题讨论】:

    标签: reactjs axios react-hooks


    【解决方案1】:

    您不能直接从函数重定向。如果你想从函数重定向,那么你可以使用this.props.history.push('/inventory');

    还有另一种使用状态重定向的方法。

    const[login,setIsLoggedIn]=useState(false)
    
    if (response.status === 200) {
           setIsLoggedIn(true);
    }
    if(login){
           return <Redirect to='/inventory'/>
    }
    
    return(
           //Main function return
    );
    

    【讨论】:

      【解决方案2】:

      如果你使用 react-router-dom,你可以从 documentation 看到这个例子,你可以在 here 看到类似的问题

      【讨论】:

        【解决方案3】:

        由于是 axios 调用,所以总是推荐使用 this.props.history.push()。

        确保在使用此功能时,您已经使用 withRouter 来路由您的组件。

        import React, { Component } from 'react';
        import { withRouter } from 'react-router-dom';
        import axios from 'axios';
        
        class App extends Component {
            ...
            const handleSubmit = e => {
            e.preventDefault();
            console.log(adminLogin)
        
            axios
              .post("/api/Authentication", adminLogin)
              .then(function(response) {
                if (response.status === 200) {
                  setIsLoggedIn(true);
                  this.props.history.push('/inventory');
                }
                setAdminLogin(response.data);
                console.log(response);
              })
              .catch(function(error) {
                console.log(error);
              });
            }
            ...
        }
        
        export default withRouter(App);
        

        如果你不使用 withRouter 包装你的组件,history 对象将不会出现在 this.props 中,因此会引发错误。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-09-19
          • 1970-01-01
          • 2020-09-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多