我正在实现一个简单的登录页面,我想在选择身份后将用户转发到另一个页面/路径。
import {useState} from "react";
import { Navigate } from 'react-router-dom';
import Container from 'react-bootstrap/Container';
import Select from 'react-select';
import './Login.css';
export default function Login(){
const [technician,setTechnician]=useState();
let options=[
{label:"Jack", value:"2432244cvdsffsd2342434"}
];
let doLogin=()=>{
if (technician){
sessionStorage.setItem("technican",JSON.stringify(technician));
return <Navigate to='/request'/>
}else {
alert("Please select your name to login.");
}
}
let handleChange=(value)=>{
setTechnician(value);
}
return (
<Container>
Login:
<Select
isClearable
onChange={handleChange}
options={options}
placeholder="Please select your name to login"/>
<button onClick={doLogin}>Login</button>
</Container>
)
}
我正在使用react-router v6。
“react-router-dom”:“^6.0.2”
预期结果:
- 用户从下拉列表中选择身份。
- 点击“登录”按钮。它应该将用户转发到“/request”路径
实际结果:
页面不会将用户转发到“/request”路径。
你能告诉我问题是什么吗?
最佳答案
你可以通过react-router-dom v6中的useNavigate
钩子(Hook)来做到这一点,如下所示:
import { useNavigate } from 'react-router-dom';
...
export default function Login(){
const navigate = useNavigate();
...
let doLogin=()=>{
if (technician){
sessionStorage.setItem("technican",JSON.stringify(technician));
navigate('/request');
}else {
alert("Please select your name to login.");
}
}
}
关于reactjs - 如何将用户转发到 react 中的其他页面/路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70344365/