arrayHelper函数运行后访问更新的FormikProps

时间:2019-01-10 19:00:15

标签: javascript reactjs formik

我有以下代码:

  addLineItem = (formProps: FormikProps<MyEntity>, arrayHelpers: ArrayHelpers) => {
    arrayHelpers.push(getNewEntity(formProps.values.date));
    reassignLineItemIds(formProps);
  };

我遇到的问题是reassignLineItemIds需要formProps中的更新值,并且formProps具有arrayHelpers.push()之后,我无权访问 interface ConnectedProps { delay?: number; onChange: (prevProps: FormikProps<MyEntity>, nextProps: FormikProps<MyEntity>) => void; } interface OwnProps extends ConnectedProps { formik: FormikProps<FormikValues>; } class FormChangeHandler extends Component<OwnProps> { onChange = debounce(this.props.onChange, this.props.delay || 0); componentDidUpdate(prevProps: OwnProps) { const { formik } = this.props; const { isValid } = formik; const hasChanged = !isEqual(prevProps.formik.values, formik.values); const shouldCallback = isValid && hasChanged; if (shouldCallback) { this.onChange(prevProps.formik as FormikProps<MyEntity>, formik as FormikProps<MyEntity>); } } render() { return null; } } const connected = connect<ConnectedProps>(FormChangeHandler); export { connected as FormChangeHandler }; 的更新版本运行。

我遇到的一个解决方案涉及创建以下组件:

<Form>

然后在我的Formik <FormChangeHandler onChange={ (prevProps: FormikProps<MyEntity>, nextProps: FormikProps<MyEntity>) => { if (getLineItemCount(prevProps.values) !== getLineItemCount(nextProps.values)) { reassignLineItemIds(nextProps); } }} /> 中包含以下内容:

 app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
                routes.MapRoute(
                    name: "rentals",
                    template: "{controller=Rentals}/{action=~/rentals/Index}/{id?}");

            });

此方法有效,但是会对性能造成负面影响,似乎就像是要跳过去的疯子。

1 个答案:

答案 0 :(得分:0)

最好的解决方案似乎仍然有些破绽,那就是加入验证。调用(某些)数组助手时会触发验证,因此该机制可以用作状态更新时的回调。仍然不是理想的解决方案,但看起来这是目前最接近的解决方案。