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

时间:2020-10-30 23:54:54

标签: javascript reactjs react-props

我必须在下拉菜单上单击两次,以使状态更新页面上显示的内容。我提供了一个视频和一些代码片段。我该如何改变呢?

enter image description here

父类组件(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抓取

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

渲染应用

  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;

儿童无类组件(菜单):

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);
  }

返回菜单

  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>
  );
}

1 个答案:

答案 0 :(得分:3)

state异步更新,您不确定在调用props.regionUpdate之前状态更新是否会发生。只需直接传递目标值即可。

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