簡體   English   中英

將react-select異步與loadOptions和redux-form一起使用

[英]Using react-select Async with loadOptions and redux-form

我正在使用react-select庫來顯示選擇框。 我正在使用Select.Async因為我需要從API中提取選項。 我將SelectloadOptions一起loadOptions ,它在初始頁面渲染期間起作用。 但是,我也在使用redux-form ,它可以動態change Field的值(使用change )。 但是,當我像這樣更改Field的值時,輸入的值的確發生了變化(並且我可以驗證這一點),但是從來沒有再次調用react-select的loadOptions (即使我認為它應該監聽一個價值變化)。 我的問題是,是否有一種方法可以在每次輸入值更改時動態調用loadOptions?

謝謝,

編輯:在github上回答這里

也許比這更好的解決方案,但是一種快速的方法是為Select.Async組件設置一個ref ,並在觸發更改操作時(例如,輸入的更改-您的情況或一個按鈕單擊事件-如在下面的代碼中),您可以更新其選項。 我在他們的文檔示例中使用了類似的示例。

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>
    )
  }
}

 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實現的代碼

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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