使用带反射的Formik

时间:2018-05-30 16:56:51

标签: reactjs formik

我在React中使用Formik表单。每当用户提交(handleSubmit)时,我都会选择是否放弃更改或保留更改。

在我的渲染中,

      <Formik
        initialValues={this.state.experiment}
        onSubmit={this.handleSubmit}
        component={formikProps => (
          <ExperimentForm {...formikProps} submitText="Save Changes" />
        )}
      />

handleSubmit()

  handleSubmit(formdata: any, actions: any) {
    const data = processFormData(formdata);

    let changes = this.detectChanges(this.state.experiment, data);

    this.setState({ tempFormData: data });
    // changed field exists
    if (changes.length !== 0) {

      this.setState({ 
        isDialogOpen: true,
        changedFields: changes,
      });

    } else {
      actions.setSubmitting(false);
      this.setState({
        message: 'Nothing Changed',
      });
    }
  }

keepChanges()和discardChanges()

  keepChanges () {

    const data = this.state.tempFormData
    makeMutation(UpdateExperimentQuery, {
      update: {
        id: this.props.match.params.id,
        data,
      },
    })
      .then(responseData => {
        console.log(responseData)
        this.setState({ isDialogOpen: false });

        this.props.history.push('/i/experiments');

      })
      .catch(err => {

        this.setState({
          message: 'Error Updating Experiment',
        });
        console.log(err);
      });

  }

  discardChanges () {
      this.setState({ isDialogOpen: false });
      this.componentWillMount();
  }

keepChanges()使用给定字段成功更新数据,但discardChanges只关闭对话框,但未将数据重置为原始值,即使我尝试调用componentWillMount()取出并在DB中呈现原始未更改的数据。

当我选择放弃更改时,如何重置字段?

修改

  discardChanges () {
      this.formik.current.resetForm();
      this.setState({ isDialogOpen: false });
      this.componentWillMount();
  }

//当我做React.createRef()时出错;

class EditExperiment extends Component<EditExperimentProps, EditState> {
  constructor(props: EditExperimentProps) {
    super(props);
    this.formik = React.createRef();

    this.state = {
      experiment: null,
      message: null,
      changedFields: [],
      isDialogOpen: false,
      tempFormData: []
    };

    this.handleSubmit = this.handleSubmit.bind(this);
    this.clearMessage = this.clearMessage.bind(this);
    this.detectChanges = this.detectChanges.bind(this);
    this.keepChanges = this.keepChanges.bind(this);
    this.discardChanges = this.discardChanges.bind(this);
  }

EDIT2

type EditExperimentProps = {
  history: RouterHistory,
  match: Match,
  experiments: ExperimentsState,
  refetch: () => void,
};
type EditState = {
  experiment: ?Experiment,
  message: ?string,
};

class EditExperiment extends Component<EditExperimentProps, EditState> {
  constructor(props: EditExperimentProps) {
    super(props);
    this.formik = React.createRef();

    this.state = {
      experiment: null,
      message: null,
      changedFields: [],
      isDialogOpen: false,
      tempFormData: []
    };

    this.handleSubmit = this.handleSubmit.bind(this);
    this.clearMessage = this.clearMessage.bind(this);
    this.detectChanges = this.detectChanges.bind(this);
    this.keepChanges = this.keepChanges.bind(this);
    this.discardChanges = this.discardChanges.bind(this);
  }

2 个答案:

答案 0 :(得分:4)

要重置Formik,您需要致电resetForm - 请参阅示例here

  handleSubmit(formdata: any, actions: any) {
    ...

    // changed field exists
    if (changes.length !== 0) {
      ...
    } else {
      actions.setSubmitting(false);
      actions.resetForm();
    }
  }

编辑:

还有另一种方法可以通过使用react ref来获取“操作”并在组件中的任何位置调用它们:

constructor(props) {
  super(props);
  this.formik = React.createRef();
}

//somewhere in render

<Formik
  ref={this.formik}
  initialValues={this.state.experiment}
  onSubmit={this.handleSubmit}
  component={formikProps => (
    <ExperimentForm {...formikProps} submitText="Save Changes" />
  )}
/>

// now somewhere else in the same component ...
componentDidUpdate(prevProps) {
  if(somethingHappend) {
    if(this.formik.current) {
      this.formik.current.resetForm();
    }
  }
}

答案 1 :(得分:2)

要使用resetForm时,需要包括初始状态。示例:

    this.formik.current.resetForm(this.initialState.experiment);

这意味着您还需要保存initialState:

constructor(props) {
    super(props);
    this.initialState = this.state;
}