【问题标题】:React Recompose : Method created in WithStateProps is not accessibleReact Recompose:在 WithStateProps 中创建的方法不可访问
【发布时间】:2019-04-24 07:34:21
【问题描述】:

我正在使用 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)
     }
   }
})

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

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

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

【问题讨论】:

  • 在您使用withFormikHoc的地方添加您的setReady
  • 已经通过添加添加:WrappedProps

标签: javascript reactjs typescript recompose


【解决方案1】:

好吧,我发现问题是我的错误,在我的compose 中,我在withStateHoc 和withIsEligibleStateHoc 之前添加了withFormikHoc,这就是错误的原因。带上他们后,第一个问题就解决了。

【讨论】:

    【解决方案2】:

    您没有正确获取道具。你的解构器是错误的。

    它应该是这样的:

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

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

    你应该做什么:

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

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

    编辑

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-02-21
      • 2019-05-24
      • 2021-07-05
      • 1970-01-01
      • 2016-05-26
      • 2018-09-27
      • 1970-01-01
      相关资源
      最近更新 更多