我是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;
}
}
最后,我将孩子下拉列表使用handleGetCountriesByRegion为options:
<select id="Countries" value={this.state.userCountry} onChange={this.handleCountryChange}>
{this.handleGetCountriesByRegion(this.state.userRegionId)}
</select>
它工作正常,但问题handleGetCountriesByRegion似乎被调用了两次。如何确保此函数仅被调用一次?另外,我想知道这是否是正确的方法。
白衣非少年
相关分类