【发布时间】:2019-07-28 22:54:00
【问题描述】:
我正在使用 Formik 效果库来控制我的 onChange 效果。但是 Formik 效果库已损坏,所以我需要编写自己的效果来触发 Formik onChange() 函数。我为我的<Effect /> 写了一个class componentWillReceiveProps 组件。但是,我所有的组件都是功能组件。我被要求将我的class 组件重构为功能组件。我仍然是 React 的初学者,所以我正在努力如何重构它。
这是我的班级<Effect /> 组件
// TODO: refactor with HOOK!
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'formik';
class Effect extends React.Component {
componentWillReceiveProps(nextProps) {
const { formik } = this.props;
const { onChange } = this.props;
const { values, touched, errors, isSubmitting } = formik;
const {
values: nextValues,
touched: nextTouched,
errors: nextErrors,
isSubmitting: nextIsSubmitting
} = nextProps.formik;
if (nextProps.formik !== formik) {
onChange(
{
values,
touched,
errors,
isSubmitting
},
{
values: nextValues,
touched: nextTouched,
errors: nextErrors,
isSubmitting: nextIsSubmitting
}
);
}
}
// eslint-disable-next-line
render() {
return null;
}
}
Effect.defaultProps = {
formik: {
errors: {},
touched: {},
values: {},
isSubmitting: false
},
onChange: () => {}
};
Effect.propTypes = {
formik: PropTypes.shape({
errors: PropTypes.shape({}),
touched: PropTypes.shape({}),
values: PropTypes.shape({}),
isSubmitting: PropTypes.bool
}),
onChange: PropTypes.func
};
export default connect(Effect);
在我的范围内,我返回
<Effect
onChange={(currentFormikState, nextFormikState) => {
if (
currentFormikState &&
nextFormikState &&
currentFormikState.values.pdsaType !==
nextFormikState.values.pdsaType
) {
resetForm(initialValues[nextFormikState.values.type]);
setType(nextFormikState.values.type);
}
}}
/>
此效果的目的是在用户选择不同类型的表单时重置初始值,因为初始值只呈现一次。并且当前的 Formik 库不支持 onChange() 函数。
currentFormikState 是 Formik 渲染的初始值,nextFormikState 是用户选择的 type 值。
【问题讨论】:
标签: javascript reactjs formik