简体   繁体   English

在 React.js 中,我的状态不是在第一次点击时更新,而是在第二次点击时更新

[英]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):父类组件(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 API 获取

  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. state更新是异步的,你不能确定状态更新会在props.regionUpdate被调用之前发生。 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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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