简体   繁体   中英

in React.js, my state isn't updating on the first click but the second one

I have to click items on my dropdown menu twice in order for the state to update the content shown on the page. I included a video and some code snippets. How can I go about changing that?

在此处输入图片说明

Parent Class Component (APP):

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      region: 'Africa', // region is owned by Parent component
      countries: [],
    }
  }

  updateRegion = (type) => {
    this.setState({
      region: type
    })
  }

API FETCH

  componentDidMount(){
    const apiURL = `https://restcountries.eu/rest/v2/all`;
      const response = fetch(apiURL)
        .then(resp => resp.json())
        .then(data => {
          this.setState({
            countries: data
          });
        })
  }

Rendering App

  render() {
    return (
      <div className="App">
      <section>
        <div id="search">
          <div id="search_dropdown">
            <Menu regionUpdate = {this.updateRegion}/>
          </div>
        </div>

        <CountryList countries = {this.state.countries} region = {this.state.region}  />
      </section>
    </div>
      )
  }
}

export default App;

Child Classless Component (Menu):

export default function SimpleMenu(props) {
  const [type, updateType] = React.useState('Africa');

  const onRegionClick = (e) => {
    updateType(e.target.innerText);
    console.log(e.target.innerText);
    props.regionUpdate(type);
  }

Returning Menu

  return (
    <div>
      <Button>
        Filter by Region
      </Button>
      <Menu>
        <MenuItem onClick = {onRegionClick}> Africa </MenuItem>
        <MenuItem onClick = {onRegionClick}> Americas </MenuItem>
        <MenuItem onClick = {onRegionClick}> Asia </MenuItem>
        <MenuItem onClick = {onRegionClick}> Europe </MenuItem>
        <MenuItem onClick = {onRegionClick}> Oceania </MenuItem>
      </Menu>
      
    </div>
  );
}

The state updates asynchronously, you can't be sure that the state update will happen before props.regionUpdate is called. Just pass the target value directly.

const onRegionClick = (e) => {
   updateType(e.target.innerText);
   // console.log(type);  ---> it would log the old, previous value
   props.regionUpdate(e.target.innerText);
}

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