簡體   English   中英

在 React.js 中,我的狀態不是在第一次點擊時更新,而是在第二次點擊時更新

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

我必須兩次單擊下拉菜單上的項目才能使狀態更新頁面上顯示的內容。 我包含了一個視頻和一些代碼片段。 我該如何去改變它?

在此處輸入圖片說明

父類組件(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>
  );
}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM