简体   繁体   中英

In React, which value should I rely on when doing a fetch in a dropdown? the e.target value or the value from the state

what is the best practice for this kind of stuff?

handleChange = e => {
    const { value } = e.target;
    this.setState({ selectedOption: value });
    this.fetchrepos(value);
  };



handleChangeVersion2 = e => {
    const { value } = e.target;
    this.setState({ selectedOption: value }, () => {
      this.fetchrepos(this.state.selectedOption);
    });
  };

Here is the code https://codesandbox.io/s/cold-dust-ygfos

Neither. Each function should have a single, clearly defined , objective ( Single Responsibility Principle ). One to handle changes to state, another to handle side-effects like data fetching. You shouldn't couple behaviors together.

You should use one of the component lifecycle functions to pick up on the selection value updating in state and make the data fetch. componentDidUpdate is the one.

handleChange = e => {
  const { value } = e.target;
  this.setState({ selectedOption: value });
};

componentDidUpdate(prevState) {
  if (prevState.selectedOption !== this.state.selectedOption) {
    fetchRepos(this.state.selectedOption);
  }
}

You should relay on the e.target value as the setState is an async function. But if you trigger the api call on state change then rely on state value and trigger your api call in lifecycle methods.

What you have done that is also better solution to fetch api as a callback of setState()

  handleChangeVersion2 = e => {
    const { value } = e.target;
    this.setState({ selectedOption: value }, () => {
      this.fetchrepos(this.state.selectedOption);
    });
  };

  async fetchrepos(searcTerm) {
    const response = await fetch(
      `https://api.github.com/search/repositories?q=${searcTerm}`
    );
    const data = await response.json();
    this.setState({ data: data.items });
  }

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