簡體   English   中英

第一次選擇“選擇”選項但第二次沒有選擇時,React / Redux失敗

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM