[英]React/Redux fails when a Select option is selected the first time but not the second
我正在开发一个React / Redux CRUD表单 。
已解决 :由于我正在使用Redux,因此应在调用API之后由Redux更改状态,而不是通过this.setState进行更改 。
逻辑非常基本:用户在OwnerList中选择所有者,然后在第二个Select Form元素中显示他/她的宠物的列表。
当用户从Select元素中选择所有者时,将调用此方法:
changeOwner(value) {
this.setState({owner_id: value['value']}); // set owner
let action = ApposActionCreators.getPets(value['value'], true);
this.props.dispatch(action); // API call
this.setState({pets_options: this.props.pets_options}); // set pets
}
这是所有者选择元素:
<Select name="owners" options={this.state.owners_options} value={this.state.owner_id} onChange={this.changeOwner.bind(this)} />
宠物元素:
<Select ref="petSelect" autofocus options={this.state.pets_options} name="selected-pet" value={this.state.pet_id} onChange={this.changePet.bind(this)} searchable={true} />
我可以成功加载所有者列表,但是当用户第一次从所有者列表中选择一个元素时,即使action和reducer运行正常,也不会填充pets元素。 第二次及以后的时间都可以正常工作,问题出在第一次。
我尝试了一些类似设置setTimeout的操作,但是并不能解决问题。
this.props.dispatch()
不保证在调度调用后立即在this.props.pets_options
具有正确的值。 如果要对新的props值执行某些操作,则必须使用componentWillReceiveProps
生命周期方法。
componentWillReceiveProps(nextProps) {
this.setState({pets_options: nextProps.pets_options})
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.