首页 > 解决方案 > 在 React/Redux 中获取 Dispatch 的价值

问题描述

我正在尝试通过 twilio api 实现帐户验证,它向用户发送代码,它应该将状态设置generatedCode为该值,但我很难获得调度的该值。如果我await用 axios 做一个简单的调用,它可以正常工作,但对于调度来说就不那么好了

行动:

export const attemptRegisterVerify = (phone) => async (dispatch) => {
  dispatch(registerVerifyBegin());
  await postRegisterVerifyPhone(phone)
    .then((res) => {
      dispatch(registerVerifySuccess(res.data));
    })
    .catch((error) => {
      dispatch(registerVerifyFail(error));
    });
};

处理验证:

const handleVerification = async (values) => {
    const { email, phone } = values;
    setModal(true);
    try {
      const response = await axios.post(
        'http://localhost:8000/api/v1/auth/register/check-duplicate',
        {
          email,
          phone,
        }
      );

      if (response.data.success) {
        switch (response.data.message) {
          case 0:
            try {
              const response = await dispatch(
                attemptRegisterVerify({ to: phone })
              );
              console.log(response);
              // if (response.data.success) {
              //   setGeneratedCode(response.data.message);
              //   console.log(generatedCode);
              // } else {
              //   console.log(response.data.message);
              // }
            } catch (error) {
              console.log(error);
            }
            break;

          case 1:
            console.log('Email Address already in use.');
            break;
          case 2:
            console.log('Phone number already in use.');
            break;
          case 3:
            console.log('Email and Phone in use.');
            break;
        }
      } else {
        console.log(response.data.message);
      }
    } catch (error) {
      console.log(error);
    }
  };

console.log(response) 返回undefined。有没有办法让它等到调度完成,然后继续?


export const attemptRegisterVerify = (phone) => async (dispatch) => {
  dispatch(registerVerifyBegin());
  await postRegisterVerifyPhone(phone)
    .then((res) => {
      dispatch(registerVerifySuccess(res.data));
      return res.data; // return console.log(res.data) works
    })
    .catch((error) => {
      dispatch(registerVerifyFail(error));
    });
};

标签: reactjsreact-redux

解决方案


Dispatch 返回您在函数调用中返回的内容。在异步 thunk 的情况Promise<void>下,除非您返回某些内容,否则它将默认返回。

如果在您的attemptRegisterVerifythunk 中,如果您添加return 'test'到它的末尾,那么您console.log(response)将记录'test'.

在非 thunk 中,调度的返回值将是生成的操作。


推荐阅读