首页 > 解决方案 > 在使用打字稿做出本机反应时,在redux中出现类型错误

问题描述

我正在尝试存储是否已验证电话号码的布尔值。

在我的登录组件中:

await dispatch(setOTPVerified(data.is_phone_verified));

动作.tsx:

export const OTP_VERIFIED = 'OTP_VERIFIED';
export const setOTPVerified = (OTPVerified: boolean) => {
  return {
    type: OTP_VERIFIED,
    OTPVerified,
  };
};

减速器.tsx:

export interface ExtrasParams {
  OTPVerified?: any;
}

const initialData: ExtrasParams = {
    OTPVerified: false,
  };

const extrasReducer = (state = initialData, action: any): ExtrasParams => {
    switch (action.type) {
      case OTP_VERIFIED:
        state = {...state, OTPVerified: action.OTPVerified};
        return state;
      default:
        return state;
    }
  };

传奇.tsx:

function* getOTPVerified(action: any) {
  yield put({
    OTPVerified: action.OTPVerified,
  });
}

export default function* extrasSaga() {
  yield takeLatest(OTP_VERIFIED, getOTPVerified);
}

控制台错误:

Error: Actions may not have an undefined "type" property. Have you misspelled a constant?
The above error occurred in task getOTPVerified
    created by takeLatest(OTP_VERIFIED, getOTPVerified)

我是在 react native 中使用 typescript 的新手,并且在 redux 中声明类型不是很清楚。我一直在尝试不同的类型,但我无法清除此错误。

标签: typescriptreact-nativereduxreact-reduxredux-saga

解决方案


错误信息很清楚。效果创建者put(action)接受具有以下接口的 redux 操作:

export interface Action<T = any> {
  type: T
}

redux dispatch(action) doc 说:

操作必须有一个type字段来指示正在执行的操作的类型。

源码中我们可以看到dispatch()方法的参数验证。

if (typeof action.type === 'undefined') {
  throw new Error(
    'Actions may not have an undefined "type" property. You may have misspelled an action type string constant.'
  )
}

必须为操作对象提供一个type字段。像这样的东西:

function* getOTPVerified(action: any) {
  yield put({
    type: 'OTP_VERIFIED_SUCCESS',
    OTPVerified: action.OTPVerified,
  });
}

推荐阅读