【问题标题】:usereducer won't update stateusereducer 不会更新状态
【发布时间】:2020-09-24 16:41:57
【问题描述】:

我对 React 很陌生,遇到了 useReducer。 如果我在这里粘贴我的代码会很长,因为它涉及到组件,useContext和useReducer。所以我将只粘贴一些代码。 我对 try and catch 循环中的状态有疑问。 我的 reducer 启动了一个使用 firebase signInWithEmailAndPassword() 的登录方法。我做错了 try and catch 循环吗?我可以在 console.log 中看到错误消息,但我的状态不会随着错误消息而更新,无论是在 then().catch() 还是在 try and catch 循环中。

  const loginUser = (usename, password, state) => {
    try{

      const res = auth.signInWithEmailAndPassword(email, password).then( user => {
          return {...state, userid: user.uid}
        }).catch(error => {
              return {...state, error: error.message}
        })


    }catch (error) {
      console.log("oops !! error: ", error);
   
      return {...state, error: error, isLoggedIn:false, isLoading:false};
    }
}

export const storeReducer = (state, action) => {
    switch (action.type) {
      case USER_LOGIN: 
      
        return loginUser(action.username, action.password, state);
          
      default:
        return state;
    }
  };

上面的代码是一个简化版本,我在使用 useReducer 更新状态时遇到了问题。

【问题讨论】:

    标签: reactjs use-reducer ionic-react


    【解决方案1】:

    我会把你的 loginUser 函数改成这样的......

    const loginUser = async (usename, password, state) => {
        try{
          const response = await auth.signInWithEmailAndPassword(email, password)
    
          return // return user here
        }catch (error) {
          console.log("oops !! error: ", error);
       
          return // return error here
        }
    }
    

    并且你应该根据这个函数的返回来调度一个action,或者从这个函数调度。您应该将此函数放在您的减速器中,因为它是异步的,并且您的减速器应该是一个纯函数

    应该更像……

    loginUser.then(data => {
      // dispatch accordingly
    })
    

    【讨论】:

    • 感谢@Jason 的回复。我做了相应的更改,但它返回了 Promise ..我该如何处理 Promise ?如何获取 Promise 返回的值?
    • 请问您要返回什么?或者您在等待响应后有什么代码?
    • 它返回了具有正确状态值的 Promise,但状态值没有更新为 useContext 值。承诺状态值显示在i.ibb.co/KmxLjx0/Promise.png,而上下文值显示在i.ibb.co/RzZtw6g/Context.png
    • 嗨,Jason,异步等待导致获取状态延迟。我使用 try/catch 和 async/await 尝试了许多不同的方法,但无济于事。当我使用 async/await 时,useReducer 中的状态更新被延迟,它在 useReducer 中返回了初始状态。所以,我切换到没有 async/await 的普通 try/catch,但在 const response = auth.signInWithEmailAndPassword(email,password) 之后添加 const currentUser = auth.currentUser。它给了我我希望看到的结果。无论如何,感谢您的帮助
    猜你喜欢
    • 2021-01-17
    • 2022-01-05
    • 1970-01-01
    • 2021-03-02
    • 2019-08-13
    • 2021-08-17
    • 2020-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多