javascript - 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;
}
}
最后,我像这样使用handleGetCountriesByRegion
子options
下拉菜单:
<select id="Countries" value={this.state.userCountry} onChange={this.handleCountryChange}>
{this.handleGetCountriesByRegion(this.state.userRegionId)}
</select>
它工作正常,但问题handleGetCountriesByRegion
似乎被调用了两次。我怎样才能确保这个函数只被调用一次?另外,我想知道这是否是正确的方法。
解决方案
你的 componentDidUpdate() 被调用两次,原因是每当你的组件被更新时 componentDidUpdate() 被调用,然后你的函数被调用。解决方案是将先前状态与新状态进行比较,如下所示:-
componentDidUpdate(prevProps, prevState) {
if(this.state.userRegionId != prevState.userRegionId) {
this.handleGetCountriesByRegion(this.state.userRegionId);
}
}
推荐阅读
- flutter - 将图像 FlutterWebImagePicker 输出转换为文件
- c - 运行外部编译器 (godbolt) 程序集
- node.js - ExperimentalWarning:条件导出是一项实验性功能"
- netlogo - 子样本中的海龟做出不同的动作
- c++ - 不释放内部单元时内存泄漏?
- woocommerce - 更新订单状态的 Dokan 操作
- bitnami - Bitnami 中的 server.js 在哪里?
- apache - Apache 无法使用 ProxyPass 托管 ASP.NET Core 应用程序
- mysql - 在where子句MySQL中转换日期
- linux - 如何在一台服务器中的 Apache 和另一台服务器中的 Tomcat 之间配置 AJP