在react中导航到新页面不工作



当我尝试添加详细信息到注册页面时,数据被发送到MongoDB,但页面没有导航到下一个。

添加注册邮箱和密码后,提交后页面应该导航到登录页面,但不是

这是代码片段:
const response = await axios.post(`http://localhost:8000/${isSignUp ? 'signup' :  'login'}`, { email, password })

const success = response.status === 201
if (success && isSignUp) navigate ('/onboarding')
if (success && !isSignUp) navigate ('/dashboard')
} catch(error){
console.log(error)
}
}

您可以从react-router-dom包中导入useNavigate钩子,并将其用于navigate所需的页面:

import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import axios from 'axios';
export default function Signup() {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const navigate = useNavigate();
const handleSubmit = async (e) => {
e.preventDefault();
try {
const response = await axios.post(`http://localhost:8000/${isSignUp ? 'signup' :  'login'}`, { email, password });
const success = response.status === 201;
if (success && isSignUp) navigate('/onboarding');
if (success && !isSignUp) navigate('/dashboard');
} catch(error){
console.log(error);
}
}
return (
<form onSubmit={handleSubmit}>
<label>
Email:
<input type="email" value={email} onChange={(e) => setEmail(e.target.value)} />
</label>
<label>
Password:
<input type="password" value={password} onChange={(e) => setPassword(e.target.value)} />
</label>
<button type="submit">{isSignUp ? 'Sign up' : 'Log in'}</button>
</form>
);
}

相关内容

  • 没有找到相关文章

最新更新