2017-09-29 2 views
1

ユーザー入力に基づいてモデル番号を提供する非同期入力フィールドreact-selectを作成しようとしています。私のAPIは動作しています.Fetchは、ドロップダウンを設定するのに必要な正確なオプションオブジェクトを生成しています(ネットワーク要求とコンソールの両方をチェックしました)。React Select with Async - オプションをロードできません

問題は、入力を開始すると、ドロップダウンにロード中であることが表示されますが、オプションが追加されないということです。 {options: [{value: "WA501006", label: "WA501006"}]}.

これは私のコードです:

getModelsAPI = (input) => { 

     if (!input) { 
      return Promise.resolve({ options: [] }); 
     } 

     const url = `(...)?cmd=item_codes_json&term=${input}`; 

     fetch(url, {credentials: 'include'}) 
      .then((response) => { 
       return response.json(); 
      }) 
      .then((json) => { 
       const formatted = json.map((l) => { 
        return Object.assign({}, { 
         value: l.value, 
         label: l.label 
        }); 
       }) 
       return { options: formatted } 
      }) 
    } 

onChange = (value) => { 
    this.setState({ 
     value: value 
    }) 
} 

<Select.Async 
    value={this.state.value} 
    loadOptions={this.getModelsAPI} 
    placeholder="Enter Model" 
    onChange={this.onChange} 
/> 

答えて

1

私はあなたがgetModelsAPI機能から復帰する必要があると思う:

ここ

enter image description here

フェッチ呼び出しからの出力例です

getModelsAPI = (input) => { 

     if (!input) { 
      return Promise.resolve({ options: [] }); 
     } 

     const url = `(...)?cmd=item_codes_json&term=${input}`; 

     return fetch(url, {credentials: 'include'}) 
      .then((response) => { 
       return response.json(); 
      }) 
      .then((json) => { 
       const formatted = json.map((l) => { 
        return Object.assign({}, { 
         value: l.value, 
         label: l.label 
        }); 
       }) 
       return { options: formatted } 
      }) 
    } 
+0

なぜあなたは 'return'の必要性がFetchの出力である 'getModelsAPI'の戻り値ではないのか説明できますか? –

+0

'fetch'は複数の' .then() 'で連鎖可能な約束です。 'fetch'の中のそれぞれの戻り値はその値を次の' .then() 'に渡しますが、関数の外には戻りません。そのためには、約束の前にあなたは戻りが必要です –

関連する問題