从函数参数

时间:2018-04-19 14:56:38

标签: javascript reactjs flowtype

某些背景

我正在制作一个表单(使用react-final-form),并监视某些表单的状态。

该库提供了一个React组件(FormSpy),它允许您订阅表单状态各个部分的更改,并仅使用表单状态的那些部分调用回调函数(从不{{1表单状态确实发生变化时。}或null)。

相关代码的简化版

undefined

...并且只订阅对表单的// Represents the current state of the form. // values is an object with each field in the form as a key // submitting is true if a submission is currently in progress type FormState = { values?: Object, submitting?: boolean, }; // Indicate which form state changes to subscribe to type Subscription = { values?: boolean, submitting?: boolean, }; type RenderCallback = (formState: FormState) => React.Node; // The function that is automatically called with the subscribed-to parts of the form state when something changes function FormSpy(subscription: Subscription, render: RenderCallback) { // This is available to the component const relevantFormState = getRelevantFormStateBySubscription(subscription); // Call the callback with the relevant form state return render(relevantFormState); } (非values状态)的更改,您可以像这样使用它(假设表单有一个名为“email”的字段,其值为“ test@test.xyz“:

submitting

我的问题

当人们阅读代码时,我们知道function renderEmail = ({ values: { email }}) { return <div>{email}</div>; } const theSpy = ( <FormSpy subscription={{ values: true }} renderCallback={renderEmail} /> ); 将是一个对象,因为我们只是订阅了values

但是,valuesvalues类型中的Maybe类型,因此Flow会强制我们在访问其中的任何内容之前检查FormState是否存在(在这种情况下,选择values)。

这样可以正常工作,但不必要地膨胀:

email

我也可以通过将function renderEmail({ values }) { if (values == null) { throw new Error('This never happens because of our subscription'); } return <div>{values.email}</div>; } const theSpy = ( <FormSpy subscription={{ values: true }} renderCallback={renderEmail} /> ); 置于我构造// $FlowFixMe的行的上方来解决问题,但这也会使该行上的所有其他错误无效并且无法解决我的问题。

我的问题

是否可以使用values参数中的对象键来派生可用作subscription的参数类型的类型,这样我们就不必执行这些不必要的null / undefined check?

也就是说,如果renderCallback带有subscription,我想创建values: true的专用版本,例如FormState,而不是{ values: Object }

密钥在{ values?: Object, submitting?: booolean }subscription中始终具有相同的名称 - 我不确定这是否重要。

可以这样做吗?

0 个答案:

没有答案
相关问题