我是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似乎被调用了两次。如何确保此函数仅被调用一次?另外,我想知道这是否是正确的方法。
2 回答

白衣非少年
TA贡献1155条经验 获得超0个赞
之所以handleGetCountriesByRegion被称为两次,是因为您在每次状态更新和DOM中都使用了它:
componentDidUpdate(){
this.handleGetCountriesByRegion(this.state.userRegionId); <--- here
}
<select id="Countries" value={this.state.userCountry} onChange={this.handleCountryChange}>
{this.handleGetCountriesByRegion(this.state.userRegionId)} <--- and here
</select>
您的结构很好,但是请考虑handleGetCountriesByRegion将组件重构为接收ID作为道具并根据其更改UI的组件。
添加回答
举报
0/150
提交
取消