为了账号安全,请及时绑定邮箱和手机立即绑定

在ReactJS受控组件中进行级联下拉

在ReactJS受控组件中进行级联下拉

Smart猫小萌 2021-05-11 21:37:01
我是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的组件。


查看完整回答
反对 回复 2021-05-20
  • 2 回答
  • 0 关注
  • 317 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信