首页 > 解决方案 > 箭头函数中的隐式返回

问题描述

我收到一个奇怪的警告,我Expected to return a value in arrow function在以下代码中

export const loginUser = userData => dispatch => {
    axios.get("http://localhost:5000/users")
        .then((res)=>{
            res.data.map(user => {                     <---- warning occurs here
                if(user.email === userData.email){
                    if(user.password === userData.password){
                        localStorage.setItem("user", JSON.stringify(user));
                        dispatch(setCurrentUser(user));
                    }
                }
            })
        })
        .catch((err)=>dispatch({
            type: GET_ERRORS,
            payload: err.data
        }))
}

但我认为不需要return在箭头函数中声明一个显式,我做错了什么?我怎样才能解决这个问题?

标签: javascriptreactjs

解决方案


例如,当您使用这样的地图时

const map1 = array1.map(x => x * 2);

您无需使用显式返回

但在场景中

const map1 = array1.map(x => {
return x*2
});

主要区别在于花括号需要返回声明。

您提供的代码正在执行调度操作,在这种情况下它不需要任何返回,我建议使用 foreach 循环 [更新]

export const loginUser = userData => dispatch => {
    return axios.get("http://localhost:5000/users")
        .then((res)=>{
            res.data.foreach(user => {                     <---- warning occurs here
                if(user.email === userData.email){
                    if(user.password === userData.password){
                        localStorage.setItem("user", JSON.stringify(user));
                        dispatch(setCurrentUser(user));
                    }
                }
            })
        })
        .catch((err)=>dispatch({
            type: GET_ERRORS,
            payload: err.data
        }))
}

推荐阅读