我正在开发一个 React/Redux CRUD form .
已解决:由于我使用的是 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} />
我可以成功加载所有者列表,但是当用户第一次从所有者列表中选择一个元素时,即使操作和 reducer 工作正常,宠物元素也不会填充。 第二次及以后一切正常,问题出在第一次。
我尝试了一些方法,例如设置 setTimeout,但这并没有解决问题。
最佳答案
this.props.dispatch()
不保证在调度调用后立即在 this.props.pets_options
中获得正确的值。如果您想使用新的 props 值执行某些操作,则必须使用 componentWillReceiveProps
生命周期方法。
componentWillReceiveProps(nextProps) {
this.setState({pets_options: nextProps.pets_options})
}
关于javascript - 当第一次选择 Select 选项但第二次没有选择时,React/Redux 会失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38983880/