【问题标题】:in React.js, my state isn't updating on the first click but the second one在 React.js 中,我的状态不是在第一次点击时更新,而是在第二次点击时更新
【发布时间】:2020-10-30 23:54:54
【问题描述】:

我必须单击下拉菜单上的项目两次,以便状态更新页面上显示的内容。我包含了一个视频和一些代码 sn-ps。我该如何改变呢?

父类组件(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>
  );
}

【问题讨论】:

    标签: javascript reactjs react-props


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-28
      • 2018-08-11
      • 2019-11-05
      • 1970-01-01
      • 1970-01-01
      • 2020-11-10
      • 2018-02-04
      • 1970-01-01
      相关资源
      最近更新 更多