在React中提交表单时使用重定向

我一直在尝试在用户登录时重定向。该登录名可以正确地与我的数据库一起使用,并将有条件地呈现我的管理门户的新链接。我试图在获得状态码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);
      });
hjf2010yl 回答:在React中提交表单时使用重定向

您不能直接从函数重定向。如果要从函数重定向,则可以使用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
);
,

如果您使用react-router-dom,则可以从documentation看到此示例,并且可以在here中看到类似的问题

,

由于它是axios调用,因此始终建议使用this.props.history.push()。

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

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包装组件,则this.props中将不存在历史对象,因此将引发错误。

本文链接:https://www.f2er.com/3162419.html

大家都在问