reactjs - 在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>
);
}
我尝试使用重定向和链接,但它对任何一个都不起作用。任何提示/提示都会很棒。先谢谢了
解决方案
从回调中返回一个 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")
}
})
}
推荐阅读
- node.js - 在 Firebase 中按需下载文件
- javascript - 在闪亮的应用程序中将 Editor QR Scanner 包装到 DT 中
- reactjs - Strapi安装过程中依赖安装报错
- python - 如何在python上制作多项选择游戏
- ffmpeg - ffmpeg 多个输入 ss 仅在其中一个上
- azure-stream-analytics - Azure 流分析作业在使用静态引用数据时不生成输出
- go - 从文件中解析普罗米修斯指标并更新计数器
- powershell - 具有两个文本输入和下拉选择的 Powershell 表单
- php - 在 Telegram PHP API 中使用 Markdown 代码块
- sql - Postgres 关系查询