我如何在这里访问外部作用域变量?

时间:2020-03-05 14:24:54

标签: javascript reactjs react-hooks

function reducer(state = initialState, action) {
    //const [success,setSuccess] = useState(false)  :This is giving me an error:
    let success = false; //want to access this variable 
    if (action.type === LOG_USER) {
        fire.auth().signInWithEmailAndPassword(action.payload.username, action.payload.pass).then((res) => {
            console.log("entered") //this output is showing in the console
            success=true //from this line
        }).catch((e) => {

        })
    }
    if(success){
      //do something.....
    }

我想从定义的箭头函数中访问成功变量。我该怎么办?

编辑: 在达成if陈述时,成功的价值没有改变。但是流程是在箭头功能内进行的

1 个答案:

答案 0 :(得分:1)

这里的问题不是变量没有更新,而是在您希望变量更新之后进行了更新。发生这种情况是因为fire.auth().signInWithEmailAndPassword(action.payload.username, action.payload.pass)返回了一个promise,因此异步工作。

您可以通过两种主要方法解决问题:

异步/等待

要解决此问题,您可以利用新的async / await语法来处理异步代码(检查浏览器支持here)。看起来像这样:

// ...
if (action.type === LOG_USER) {
    const res = await fire.auth().signInWithEmailAndPassword(action.payload.username, action.payload.pass);
    console.log("entered"); //this output is showing in the console
    success = true; //from this line
}
// ...

移动成功处理程序

另一种受更广泛支持的方法是将成功处理程序移至promise回调中,如下所示:

// let success = false; // This is no longer needed
if (action.type === LOG_USER) {
    fire.auth().signInWithEmailAndPassword(action.payload.username, action.payload.pass).then((res) => {
        console.log("entered") //this output is showing in the console
        // Handle success here
    }).catch((e) => {
    })
}

话虽如此,您不应该分派来自减速器的请求。正如您所读的here在本文讨论redux-reducers时一样,useReducer-reducers 也是这种情况),reducer应该是 pure 函数,这意味着它将某些输入转换为某些输出,而没有任何副作用。这意味着,在给定相同的先前状态和相同操作的情况下,reducer函数应始终返回相同的结果。

因此,您不必先听LOG_USER操作,而应先登录用户,然后调度包含已登录用户信息的操作。