【问题标题】:How to redirect user to a different route after a function is completed?功能完成后如何将用户重定向到不同的路由?
【发布时间】:2021-05-04 17:22:14
【问题描述】:

目前,我们在 /signup 路由中的一个反应组件。 我有这个功能如下图

    const sendForm  = async(event) => {
    try{
        var data = {
            Name : name,
            Password : password,
            Email : email,
        };
        await axios.post("api/users/", data);
    }
    catch(err){
        console.log("there was an error sending new user through post");
        console.log(err)
    }
}

这个函数在一个反应​​组件中,现在我需要确保在这个sendForm函数完成后,用户应该被重定向到/login路由。请帮我怎么做??

【问题讨论】:

  • 您是否尝试过提供的示例?让我知道它是怎么回事,如果你需要进一步的解释

标签: javascript reactjs async-await react-router web-development-server


【解决方案1】:

您可以使用 React Router 中的 useHistory() 来完成此操作。

创建一个路由<Switch>,您想在其中进行路由。

<Switch>
  <Route path="/login" component={Login} />
</Switch>

别忘了使用&lt;BrowserRouter /&gt;,你可以在index.js中使用

ReactDOM.render(
  <StrictMode>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </StrictMode>,
  rootElement
);

获取完成后,您可以将/login 推送到历史记录中,这将重定向您。

const history = useHistory();

const sendForm  = async(event) => {
  try{
      var data = {
          Name : name,
          Password : password,
          Email : email,
      };
      await axios.post("api/users/", data);
      history.push("/login"); // push route in history
  }
  catch(err){
      console.log("there was an error sending new user through post");
      console.log(err)
  }
}

不要忘记正确导入所有内容。

你可以阅读更多关于 React Router 和 hooks here

【讨论】:

    猜你喜欢
    • 2019-03-14
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 2018-05-12
    • 2023-02-03
    • 1970-01-01
    • 2020-12-14
    相关资源
    最近更新 更多