首页 > 解决方案 > 在jsx Reactjs的不同文件夹中从一个页面导航(路由)到另一个页面

问题描述

我试图当用户输入正确的电子邮件和密码时,它会将他重定向到位于 mainPage 文件夹中的主页(blog.jsx)。

当我运行我的代码时,它不会在控制台中显示任何错误,但是当您输入正确的电子邮件和密码时它不会重定向它(if-else 语句有效,因为当用户输入错误的电子邮件和密码时,会显示弹出屏幕)

这是我的代码:

  const login =() =>{
    Axios.post('http://localhost:3001/login',{
      email:email,
      password:password
    }).then((response)=>{
      if(response.data.message){
        alert(response.data.message)
      }
      else{
        return <Redirect to="../mainPage/blog" />
      }
    })
  }

完整代码:

import React, { useContext } from "react";
import {useState} from "react";
import {useHistory} from "react-router-dom";
import Axios from 'axios';
import {
  BoldLink,
  BoxContainer,
  FormContainer,
  Input,
  MutedLink,
  SubmitButton,
} from "./common";
import { Marginer } from "../marginer";
import { AccountContext } from "./accountContext";

export function LoginForm(props) {
  let history = useHistory();
  const { switchToSignup } = useContext(AccountContext);
  const [email, setEmail]=useState('');
  const [password, setPassword]=useState('');
  
  
  const login =() =>{
    Axios.post('http://localhost:3001/login',{
      email:email,
      password:password
    }).then((response)=>{
      if(response.data.message){
        alert(response.data.message)
      }
      else{
        history.push("../mainPage/blog");
      }
    })
  }

  const myFunction =()=>{
    alert("TODO");
  }
  
  return (
    <BoxContainer>
      <FormContainer>
        <Input type="email" placeholder="Email" onChange={(e)=>{setEmail(e.target.value)}}/>
        <Input type="password" placeholder="Password" onChange={(e)=>{setPassword(e.target.value)}}/>
      </FormContainer>
      <Marginer direction="vertical" margin="1em" />
      <MutedLink href="#" onClick={myFunction}>Forget your password?</MutedLink>
      <Marginer direction="vertical" margin="1em" />
      <SubmitButton type="submit" onClick={login} >Login</SubmitButton>
      <Marginer direction="vertical" margin="1em" />
      <MutedLink href="#" onClick={switchToSignup}>
        Don't have an accoun?{" "}
        <BoldLink href="#" onClick={switchToSignup}>
          Register
        </BoldLink>
      </MutedLink>
    </BoxContainer>
  );
}

我尝试使用重定向和链接,但它对任何一个都不起作用。任何提示/提示都会很棒。先谢谢了

标签: reactjsredirectjsx

解决方案


从回调中返回一个 React 元素 ( <Redirect.../>) 不会做任何事情。相反,您可以使用 React Routerhistory对象,如下所示:

  const history = useHistory();
  const login = () =>{
    Axios.post('http://localhost:3001/login',{
      email:email,
      password:password
    }).then((response)=>{
      if(response.data.message){
        alert(response.data.message)
      }
      else{
        history.push("../mainPage/blog")
      }
    })
  }

推荐阅读