简体   繁体   中英

How can I auto-fill a form using preset values and trigger a submit in a React functional component?

I have a functional component with controlled form elements. When users fill out this form, it updates state values. When they hit submit, I run a function that reads state values and makes ajax calls.

In addition to this , I want a 1-click form submission feature. To reuse code, I've been trying to update the same state values behind this 1-click link, then trigger a form submission.

However, since React functional components don't support state update callbacks, I can't call the submit function without a race condition.

How can I support both use cases cleanly?

Here's a minimal component layout to illustrate what I have.

function Exhibit(props) {
  initialForm = {/* ... */};
  const [form, setForm] = useReducer((currForm, newValues) => ({...currForm, ...newValues}), initialForm);
  function oneClickSubmit() {
    setForm({
      // Preset values
    });
    submitForm();  // RACE CONDITION HERE
  }
  function submitForm() {
    // Does stuff with form
  }
  return <div>
    <form>
      {/* Fields that call setForm */}
      ...
    </form>
    <button onClick={submitForm}>Start</button>
  </div>
}

In a class component, this would have been cakewalk. Just update state, call submitForm in the callback.

You can React.useEffect which will be invoked when form values in state are updated. Here you can validate the values and invoke the form submission instead of doing in the formSubmit

function Exhibit(props) {
  initialForm = {/* ... */};

const[isOneClickSubmit, setIsOneClickSubmit] = useState(false)

  const [form, setForm] = useReducer((currForm, newValues) => ({...currForm, ...newValues}), initialForm);


  React.useEffect(() => {
    if (validate(form) && isOneClickSubmit) {
      submitForm()
    }
  }, [form, isOneClickSubmit]);



  function oneClickSubmit() {
    setForm({
      // Preset values
    });
    setIsOneClickSubmit(true);
  }

  function submitForm() {
    // Does stuff with form
  }
  return <div>
    <form>
      {/* Fields that call setForm */}
      ...
    </form>
    <button onClick={submitForm}>Start</button>
  </div>
}

Note: Make sure you pass the form state identifier in the useEffect 2nd array param. This will make sure it gets called when value changes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM