【问题标题】:Getting type error in redux in react native with typescript在使用打字稿做出本机反应时,在redux中出现类型错误
【发布时间】:2021-09-13 09:21:47
【问题描述】:

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

在我的登录组件中:

await dispatch(setOTPVerified(data.is_phone_verified));

Action.tsx:

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

Reducer.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;
    }
  };

Saga.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 中声明类型不是很清楚。我一直在尝试不同的类型,但我无法清除此错误。

【问题讨论】:

    标签: typescript react-native redux react-redux redux-saga


    【解决方案1】:

    错误信息很清楚。效果创建者put(action) 接受redux action,界面如下:

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

    redux dispatch(action) 文档说:

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

    source code可以看到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,
      });
    }
    

    【讨论】:

    • 进行这些更改后,我没有收到任何错误,但我的应用程序没有进入下一个屏幕
    • @pratteekshaurya 如果您有新问题,请创建一个新帖子。
    猜你喜欢
    • 2021-12-07
    • 2019-04-16
    • 2022-01-06
    • 2020-09-30
    • 2019-06-29
    • 1970-01-01
    • 2021-11-13
    • 2019-12-04
    • 1970-01-01
    相关资源
    最近更新 更多