2017-07-28 43 views
0

我正在使用react-select庫來顯示一個選擇框。我正在使用Select.Async,因爲我需要從API中提取我的選項。我使用SelectloadOptions,它在初始頁面呈現期間工作。但是,我也在使用redux-form,它可以動態更改Field的值(使用change)。然而,當我像這樣改變字段的值時,輸入的值確實會改變(並且我可以驗證這一點),但是react-select的loadOptions不會再被調用(儘管我認爲它應該是在聽一個價值變化)。我的問題是,是否有一種動態方式每次輸入值更改時調用loadOptions?使用react-select異步與loadOptions和還原形式

感謝,

編輯:回答在github here

回答

-1

這可能是比這更好的解決辦法,但一個快速的設置refSelect.Async組件,並在觸發一個變化行動(如更改輸入 - 您的案例或一個按鈕單擊事件 - 如下面的代碼),您可以更新其選項。我使用their文檔示例中的類似示例。

class YourClass extends React.Component { 

    getOptions = (input, callback) => { 
    setTimeout(function() { 
     callback(null, { 
     options: [ 
      {value: 'one', label: 'One'}, 
      {value: 'two', label: 'Two'} 
     ] 
     }); 
    }, 500); 
    }; 

    updateOptions =() => { 
    this.selectAsync.state.options.push(
     {value: 'three', label: 'Three'} 
    ) 
    } 

    render() { 
    let props = this.props; 

    return (
     <div> 
     <Select.Async 
      ref={selectAsync => this.selectAsync = selectAsync} 
      loadOptions={this.getOptions} 
     /> 
     <button onClick={this.updateOptions}> 
      Load more items 
     </button> 
     </div> 
    ) 
    } 
} 
0

this.state = { 
 
      store: '', 
 
      
 
     }; 
 
     
 
     this.handleStoreSelect = this.handleStoreSelect.bind(this); 
 
      
 
      
 
      handleStoreSelect = (item) => { 
 
     this.setState({ 
 
      store: item.value 
 
     } 
 
    }; 
 
    
 
    <Select.Async 
 
           
 
           name="storeID" 
 
           value={this.state.store} 
 
           loadOptions={getStores} 
 
           onChange={this.handleStoreSelect} 
 
          />

const getStores =() => { 
 
    return fetch(
 
      "api to be hit", 
 
      { 
 
       method: 'get', 
 
       headers: { 
 
        'Content-Type': 'application/json' 
 
       } 
 
      } 
 
     ) 
 
      .then(response => { 
 
       if(response.status >= 400){ 
 
        throw new Error("error"); 
 
       } 
 
       return response.json() 
 
      }) 
 
      .then(stores => { 
 
       let ret = []; 
 

 

 
       for(let store of stores) { 
 
        ret.push({value: store._id, label: store.name}) 
 
       } 
 

 

 
       return {options: ret}; 
 
      }) 
 
      .catch(err => { 
 
       console.log('could not fetch data'); 
 
       console.log(err); 
 
       return {options: []} 
 
      }) 
 

 
};

利用這一點,我們可以獲取數據,並在loadoptions傳遞這個對象。 在課堂外複製此代碼。並且我發佈的代碼要實現的loadoptions

+0

它會工作肯定 – Piyush