在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>
);
}

我尝试使用重定向和链接,但都不起作用。任何提示/提示都很好。提前感谢:D

从回调返回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")
}
})
}

最新更新