【问题标题】:using async await in a handle submit在句柄提交中使用异步等待
【发布时间】:2021-11-09 00:02:21
【问题描述】:

我只研究了 6 个月的反应,所以也许是一个新手问题....但是我有一个处理登录表单的提交,虽然我想将用户(角色:用户)定向到一个页面和如果管理员(角色:管理员)到不同的页面,所以写了下面的代码检查用户的角色(这是一个测试项目,所以安全性并不是特别重要。我遇到的问题(为什么它不工作)是因为 currentUser 代码在 fetch 之前运行...有没有办法使用 async await 或其他方式在运行此代码之前等待 fetch ?

function handleSubmit(e) {
  e.preventDefault();
  fetch(`${process.env.REACT_APP_API}/login`, {
    credentials: 'include',
    headers: { 'Content-Type': 'application/json' },
    method: 'POST',
    body: JSON.stringify({ email: email, password: password }),
  })
    .then((res) => res.json())
    .then((userData) => {
      setCurrentUser(userData.user);
    })
    .catch((error) => console.error('FETCH ERROR:', error));

  currentUser.role === 'admin' ? history.push('/admin') : history.push('/');
}

提前感谢您的任何回答

【问题讨论】:

    标签: reactjs async-await


    【解决方案1】:

        currentUser.role === "admin" ? history.push("/admin") : history.push("/");
      
    

    .then 块内。 .then 块在 promise 解决后执行。

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then

    【讨论】:

      【解决方案2】:

      感谢您回答 @daniel-duong... 是的,虽然我已经在下面的代码中尝试过但它不起作用,但我已经添加了一个控制台日志来查看当前用户在 fetch 中的情况。返回为未定义....我不知道为什么,如果您有任何其他建议,请告诉我 - 谢谢

          e.preventDefault();
          fetch(`${process.env.REACT_APP_API}/login`, {
            credentials: "include",
            headers: { "Content-Type": "application/json" },
            method: "POST",
            body: JSON.stringify({ email: email, password: password }),
          })
            .then((res) => res.json())
            .then((userData) => {
              setCurrentUser(userData.user);
            })
            .then(() => {
              currentUser.role === "admin"
                ? history.push("/admin")
                : history.push("/");
            })
            .then(() => {
              console.log("currentuser from login", currentUser);
            })
            .catch((error) =>
              console.error("Fetch error from login handlesubmit...", error)
            );```
      

      【讨论】:

        【解决方案3】:

        如其他答案中所述,您需要在.then 内执行重定向。您缺少的一点是,当您链接 .then 方法时,只有您从前一个 then 返回的内容才能用于下一个,所以您应该做的是:

          .then((res) => res.json())
          .then((userData) => {
            setCurrentUser(userData.user);
            // if you don't return this you won't have access to it in the next .then
            return userData.user;
          })
          .then((currentUser) => {
            // so now it won't be undefined since you are returning from previous .then
            console.log("currentuser from login", currentUser);
            return currentUser;
          })
          .then((currentUser) => {
            currentUser.role === "admin"
              ? history.push("/admin")
              : history.push("/");
          })
        

        您也可以在单个 .then 方法中完成所有这些操作

        【讨论】:

        • 非常感谢您的解释 - 这很有意义且有效!希望你有一个美好的一天?✌️?
        猜你喜欢
        • 1970-01-01
        • 2021-03-17
        • 1970-01-01
        • 1970-01-01
        • 2021-10-22
        • 1970-01-01
        • 2020-07-11
        • 2018-10-18
        • 1970-01-01
        相关资源
        最近更新 更多