首页 > 解决方案 > ReactJS 控制组件中的级联下拉菜单

问题描述

我是 React 的新手。我正在尝试在受控组件中实现级联下拉。

父下拉:

<select id="Regions" className="validate" value={this.state.userRegionId} onChange={this.handleRegionChange}>
{this.handleGetRegions()}
</select>

使用handleGetRegions()安装组件时填充父下拉列表componentDidMount

onChange处理程序handleRegionChange()基本上根据所选值设置state变量。userRegionId

handleRegionChange(event){
this.setState({userRegionId: event.target.value});
}

随着state值的更新,我使用componentDidUpdate填充子下拉菜单。我使用的原因componentDidUpdate是因为state是异步更新的,并且立即值仅在此处可用。

componentDidUpdate(){
  this.handleGetCountriesByRegion(this.state.userRegionId);
}

handleGetCountriesByRegion执行:

handleGetCountriesByRegion(regionId){
  let regioncountryJSON = JSON.parse(locale["snclregioncountry-" + this.state.lang]);
  let countriesJSON = regioncountryJSON[regionId] != undefined ? regioncountryJSON[regionId].Countries : undefined;
  if (countriesJSON != undefined && countriesJSON.length > 0) {
    let countries = [];
    let defaultValue = locale["ddlCountry-" + this.state.lang];
    countries.push(<option selected disabled key={-1} value={defaultValue}>{defaultValue}</option>);
    countriesJSON.map((val) => {
      countries.push(<option key={val.id} value={val.id}>{val.name}</option>)
    });
    return countries;
  }
}

最后,我像这样使用handleGetCountriesByRegionoptions下拉菜单:

<select id="Countries" value={this.state.userCountry} onChange={this.handleCountryChange}>
  {this.handleGetCountriesByRegion(this.state.userRegionId)}
</select>

它工作正常,但问题handleGetCountriesByRegion似乎被调用了两次。我怎样才能确保这个函数只被调用一次?另外,我想知道这是否是正确的方法。

标签: javascriptreactjs

解决方案


你的 componentDidUpdate() 被调用两次,原因是每当你的组件被更新时 componentDidUpdate() 被调用,然后你的函数被调用。解决方案是将先前状态与新状态进行比较,如下所示:-

componentDidUpdate(prevProps, prevState) {
  if(this.state.userRegionId != prevState.userRegionId) {
    this.handleGetCountriesByRegion(this.state.userRegionId);
  }
}

推荐阅读