Reactjs 如何使用UseDispatch钩子等待redux操作返回的响应

Reactjs 如何使用UseDispatch钩子等待redux操作返回的响应,reactjs,react-native,redux,react-redux,Reactjs,React Native,Redux,React Redux,我对redux和 我现在正在尝试编写一个登录组件 我的redux操作是这样的 export const fetchToken = (params) => { return (dispatch) => { const config = { headers: { 'Content-Type': 'application/x-www-form-urlencoded', },

我对redux和 我现在正在尝试编写一个登录组件

我的redux操作是这样的

export const fetchToken = (params) => {
  return (dispatch) => {
        const config = {
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
        };
    return axios
      .post(`${baseUri}/api/token`, params, config)
      .then((res) => {
        dispatch({
          type: LOGGED_IN,
          payload: res.data,
        });
      })
      .catch((err) => {
        console.log(err);
        alert('Provided username and password is incorrect');
      });
  };
};
正如你所看到的,我正在回报一个承诺。我尝试在组件中使用它,但它不起作用

我正在使用
useDispatch
hooks from
react redux

我的代码是这样的

const checkValidate = () => {
        if (email.length < 1 || password.length < 1) {
            alert('Please fill all the details');
            return;
        } else {
            const params = new URLSearchParams();
            params.append('username', email);
            params.append('password', password);
            params.append('grant_type', 'password');
            dispatch(fetchToken(params)).then((res) => {
                alert('success')
            }).catch((err) => alert('not success'));
        }
        // navigation.navigate('Home');
    };
const checkValidate=()=>{
如果(email.length<1 | | password.length<1){
警报(“请填写所有详细信息”);
返回;
}否则{
const params=新的URLSearchParams();
参数append('username',email);
参数append('password',password);
params.append('grant_type','password');
调度(fetchToken(params))。然后((res)=>{
警报(“成功”)
}).catch((err)=>警报(“未成功”);
}
//导航。导航(“主页”);
};
正如你所看到的,我正在提醒成功。问题是如果我写错了用户名和密码。反应总是进入成功反应。它将向成功发出警报,然后它将向来自
fetchToken
操作的响应发出警报
(“提供的用户名和密码不正确”)我的代码有什么问题吗

而且,每当我尝试console.log
时,响应总是返回undefined

。然后((res)=>{
派遣({
类型:已登录,
有效载荷:res.data,
});
})
.catch((错误)=>{
控制台日志(err);
警报(“提供的用户名和密码不正确”);
});
从链中删除错误和结果。如果要将它们传递给下一个.then或.catch,则必须返回/重新播放:

.then((res) => {
        dispatch({
          type: LOGGED_IN,
          payload: res.data,
        });
+       return res
      })
      .catch((err) => {
        console.log(err);
        alert('Provided username and password is incorrect');
+       throw err
      });
当你这样做的时候

。然后((res)=>{
派遣({
类型:已登录,
有效载荷:res.data,
});
})
.catch((错误)=>{
控制台日志(err);
警报(“提供的用户名和密码不正确”);
});
从链中删除错误和结果。如果要将它们传递给下一个.then或.catch,则必须返回/重新播放:

.then((res) => {
        dispatch({
          type: LOGGED_IN,
          payload: res.data,
        });
+       return res
      })
      .catch((err) => {
        console.log(err);
        alert('Provided username and password is incorrect');
+       throw err
      });