简体   繁体   中英

React: how do I use onSubmit to change state?

I'm quite new to React, and have only completed a few projects with it. I'm currently trying to create a form that, using onSubmit, changes the state of "isSubmitted" from false to true. When "isSubmitted" is true, I'd like to render another component to show the results of the selection.

What's currently happening is that onChange is working and I can see the value of "selectedI" set as state in the console.log when I change it. However, when I click submit, this state of "isSubmitted" doesn't change.

My code is below. Any help is greatly appreciated!

import React, { Component } from "react";
import Results from "../components/Results";

export class Create extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedI: { value: "" },
      //   selectedC: { value: "" },
      //   selectedG: { value: "" },
      //   selectedA: { value: "" },
      isSubmitted: false,
    };
  }

  handleChange = (event) => {
    this.setState({
      selectedI: { value: event.target.value },
    });
  };

  handleSubmit = (event) => {
    event.preventdefault();
    this.setState({
      isSubmitted: true,
    });
  };

  render() {
    console.log(this.state);

    return (
      <>
        <form onSubmit={this.handleSubmit} onChange={this.handleChange}>
          <select value={this.state.value}>
            {this.props.ingredient.map((ingredient) => {
              return (
                <option value={ingredient.strIngredient1}>
                  {ingredient.strIngredient1}
                </option>
              );
            })}
          </select>
          <input type="submit" value="Submit" />
        </form>

        {this.state.isSubmitted && <Results />}
      </>
    );
  }
}

export default Create;

Inside your handleSubmit method correct the case on preventdefault . It should be preventDefault . Note the capital D. Once corrected it should stop your page from reloading and resetting your state along with it. See the code below.

handleSubmit = (event) => {
    event.preventDefault();
    this.setState({
      isSubmitted: true,
    });
  };

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