javascript - 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
不是函数!
有谁知道我在这里缺少什么?
解决方案
你没有得到正确的道具。你的解构器是错误的。
以下是它的外观:
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
。如果你愿意,你可以删除它。
推荐阅读
- python - scikit-learn v21 与 v22 的不同结果
- snowflake-cloud-data-platform - 创建和更新雪花表的工具
- jmeter - 如何将我从 HTTP 请求中获得的响应拆分为 2 个单独的数组,并在 JMeter 中的后续 HTTP 请求中使用它们?
- javascript - 在 React.js 上添加元标记
- r - 如何在 R 中读取 .MAP 文件扩展名?
- javascript - 防止特定页面直接访问
- eiffel - estudio 什么时候不检查`require`?
- java - 从另一个类获取按钮调用
- json - 在 scala 中解析 HTTP POST 响应 JSON 正文
- javascript - Vue watch 没有注意到组件属性的变化