首页 > 解决方案 > React Recompose:在 WithStateProps 中创建的方法不可访问

问题描述

我正在使用 Recompose 来定义一些方法,如下所示:

export interface WithStateProps {
  isDisabled: boolean;
  isReady: boolean;
  setDisabled(value: boolean): void;
  setReady(value: boolean): void;
}


export const withStateHoc = withState('isDisabled', 'setDisabled', false);
export const withIsEligibleStateHoc = withState(
  'isReady',
  'setReady',
  true
);

export const isReady = (value : string) => {
  return value ? true : false
};

export type WrappedProps = StepContentProps &
  FormikProps<MyAddress> &
  InjectedIntlProps & 
  AddressFormHandlers & WithStateProps;

当我想使用该setReady方法时,我收到此消息:props.setReady is not a function这是我的代码:

export const withFormikHoc = withFormik<
  WrappedProps & RouteComponentProps<{}> & InjectedIntlProps & WithStateProps,
  MyAddress
>({
 handleSubmit: async (values, { props, setSubmitting }) => {
     const addressAlreadyVerified = isReady(values.country);
     if(addressAlreadyVerified) {
        props.setReady(true)
     }
   }
})

当我将鼠标悬停props.setReady(true)在 VCode 中时,我可以看到:(method) WithStateProps.setReady(value: boolean): void

但我知道那props.setReady不是函数!

有谁知道我在这里缺少什么?

标签: javascriptreactjstypescriptrecompose

解决方案


你没有得到正确的道具。你的解构器是错误的。

以下是它的外观:

handleSubmit: async (values, { setSubmitting, ...props }) => {

含义:从您的组件道具中提取setSubmitting到它自己的变量中,并将其他所有内容放入一个props对象中。

你实际上应该做什么:

handleSubmit: async (values, { setReady, setSubmitting }) => {
  const addressAlreadyVerified = isReady(values.country);
  if (addressAlreadyVerified) {
    setReady(true)
  }
}

这样,您只需从道具中提取所需的值,而不会得到一个充满您并不真正需要的属性的对象。

编辑

如果你愿意,你可以选择不解构任何东西,你的可能最终会像这样:

handleSubmit: async (values, props) => {
  const addressAlreadyVerified = isReady(values.country);
  if (addressAlreadyVerified) {
    props.setReady(true)
  }
}

我刚刚意识到你根本没有使用setSubmitting。如果你愿意,你可以删除它。


推荐阅读