我有一个登录表单,该表单的onSubmit
属性指向以下函数:
function handleSubmit(event) {
event.preventDefault();
console.log(email);
login(email, password);
}
上面使用的登录功能从表单中获取电子邮件和密码,并在另一个文件中定义,如下所示:
export const login = async (email, password) => {
const config = {
headers: {
"Content-Type": "application/json"
}
};
const body = JSON.stringify({ email, password });
const res = await axios.post(
"http://localhost:5000/userauth/login",
body,
config
);
console.log("token: ", res.data);
return res.data;
};
现在,我想在成功登录后将用户重定向到仪表板组件。我该如何处理?我读到为此需要专用路线。但是我不知道如何在我的情况下使用它。
答案 0 :(得分:1)
假设您要在成功登录后导航到/dashboad
页
将this.props.history.push('/dashboard')
放入登录提交功能中
function handleSubmit(event) {
event.preventDefault();
console.log(email);
login(email, password);
this.props.history.push('/dashboard')
}
答案 1 :(得分:0)
我会采用更可靠的方法。 您可能希望将用户重定向到他要使用的URL,而不必使用默认URL。
因此,我将在您的登录功能上添加以下代码:
const { history, redirectTarget } = redirect;
history.push(redirectTarget);
,并将通过您的登录组件/容器传递以下数据:
let redirectTarget = 'defaultURL';
try {
redirectTarget = this.props.location.state.from/pathname;
}
catch (err) {
redirectTarget = 'defaultURL';
}
this.props.loginRequestAction(
{ username, password },
{ history: this.props.history, redirectTarget }
);