在ReactJS中登录后如何重定向到仪表板?

问题描述 投票:0回答:2

我有一个登录表单,其中的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;
};

现在,我想在成功登录后将用户重定向到仪表板组件。我该如何处理?我读到为此需要专用路线。但我无法理解如何使用它。

reactjs react-router
2个回答
1
投票

假设您要在成功登录后导航到/dashboad页面

this.props.history.push('/dashboard')放入您的登录提交功能内

function handleSubmit(event) {
    event.preventDefault();
    console.log(email);
    login(email, password);
     this.props.history.push('/dashboard')
}

-1
投票

基于我在此article中找到的内容,您可以使用{Redirect}组件。然而;你仍然可以你

window.location.href = "http://www.w3schools.com";

但是这不是ReactJs中的正确方法。

© www.soinside.com 2019 - 2024. All rights reserved.