【问题标题】:how to wait for returned response from redux actions using UseDispatch Hook如何使用 UseDispatch Hook 等待 redux 操作返回的响应
【发布时间】:2021-06-13 13:34:46
【问题描述】:

我是 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');
      });
  };
};

如您所见,我正在返回一个承诺。我尝试在组件中使用它,但它不起作用。

我正在使用来自react-reduxuseDispatch 钩子

我的代码是这样的

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');
    };

如您所见,我正在提醒成功。问题是如果我写错了用户名和密码。响应总是进入成功响应。它会提醒成功然后它会提醒来自fetchToken 操作的响应,即 alert('Provided username and password is incorrect'); 我的代码有什么问题吗?

而且每当我尝试 console.log then response 时,它总是会返回 undefined

【问题讨论】:

    标签: reactjs react-native redux react-redux


    【解决方案1】:

    当你这样做时

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

    您从链中删除错误和结果。如果您希望将它们传递给下一个 .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
          });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-11-03
      • 1970-01-01
      • 2021-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-18
      相关资源
      最近更新 更多