9

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

在我的渲染中,

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

处理提交()

  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()which 获取并呈现数据库中的原始未更改数据。

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

编辑

  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);
  }

编辑2

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);
  }
4

2 回答 2

9

要重置 Formik,您需要调用- 请参见此处resetForm的示例。

  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();
    }
  }
}
于 2018-05-30T17:03:56.413 回答
3

当您想使用 resetForm 时,您需要包含初始状态。例子:

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

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

constructor(props) {
    super(props);
    this.initialState = this.state;
}
于 2019-04-03T22:07:16.527 回答