Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs usereducer赢得';更新状态_Reactjs_Use Reducer_Ionic React - Fatal编程技术网

Reactjs usereducer赢得';更新状态

Reactjs usereducer赢得';更新状态,reactjs,use-reducer,ionic-react,Reactjs,Use Reducer,Ionic React,我是一个很新的反应和遇到useReducer。 如果我把代码粘贴到这里,它会很长,因为它涉及组件、useContext和useReducer。所以我只粘贴一些代码。 我有一个关于“尝试-捕获”循环中的状态的问题。 My reducer启动一个使用firebase Signin with Email and Password()的登录方法。我做的尝试和捕捉循环是错误的吗?我可以在console.log中看到错误消息,但我的状态不会随着错误消息而更新,无论是在then().catch()中还是在tr

我是一个很新的反应和遇到useReducer。 如果我把代码粘贴到这里,它会很长,因为它涉及组件、useContext和useReducer。所以我只粘贴一些代码。 我有一个关于“尝试-捕获”循环中的状态的问题。 My reducer启动一个使用firebase Signin with Email and Password()的登录方法。我做的尝试和捕捉循环是错误的吗?我可以在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更新状态时遇到了问题。

我会将您的
登录用户
函数更改为以下内容

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
    }
}
并且您应该基于此函数的返回或从此函数的分派来分派操作。您应该而不是将此函数放在您的reducer中,因为它是异步的,并且您的reducer应该是纯函数

它应该更像

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

谢谢@Jason的回复。我做了相应的更改,但它返回了承诺..我如何处理承诺?我如何获得承诺所返回的价值?请问您返回的是什么?或者在等待响应后,您有什么代码?它返回了带有正确状态值的承诺,但状态值未更新为useContext值。承诺状态值显示在,而上下文值显示在Hi Jason,异步等待会导致获取状态的延迟。我使用try/catch和async/await尝试了许多不同的方法,但都没有用。当我使用async/await时,useReducer中的状态更新被延迟,它在useReducer中返回初始状态。因此,我在不使用async/await的情况下切换到正常的try/catch,但在
const response=auth.currentUser=auth.currentUser
之后添加
const response=auth.signiWithEmailandPassword(email,password)
。它给了我希望看到的结果。。无论如何,谢谢你的帮助