简体   繁体   中英

How set value of Select before onChange will execute?

I'm using React. In componentDidMount I'm fetching with server => receiving data (competitors) => saving data in State. My Select is representation of this data. When Select is changing, ID of Competitor selected is saving in State so it could be send to database after submit. And it's all working. BUT when after page load I don't change anything in select, just submit, this ID is not sending, I know why (onChange not execute), but I don't know how to fix it, I can't set default State manually, because data from database can be different.

This is my State:

  state = {
    promotions: [],
    competitors: [],
    draftCompetitorIdToPromote: "",
    draftLevel: "",
    draftDate: ""
  };

This is my componentDidMount:

 componentDidMount = () => {
    fetch("http://localhost:5000/competitors")
      .then(response => response.json())
      .then(data => this.setState({ competitors: data }));
    fetch("http://localhost:5000/")
      .then(response => response.json())
      .then(data => this.setState({ promotions: data }));
  };

This is my onChange function:

 compChange = event => {
    this.setState({
      draftCompetitorIdToPromote: event.target.value
    });
  };

And this is my select:

  <select
        value={this.state.draftCompetitorIdToPromote}
        onChange={this.compChange}
        className="form-control"
      >
        {this.state.competitors.map((competitor, index) => {
          return (
            <option value={competitor._id} key={index}>
              {competitor.name}
             </option>
           );
         })}
      </select>

You need to set default value in your state, for this purpose on componentDidMount and after data load set competitors[0]._id as default value for draftCompetitorIdToPromote

componentDidMount = () => {
fetch("http://localhost:5000/competitors")
  .then(response => response.json())
  .then((data => this.setState({
         competitors: data,
         draftCompetitorIdToPromote: data[0]._id,
  }));
fetch("http://localhost:5000/")
  .then(response => response.json())
  .then(data => this.setState({ promotions: data }));
};

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