2017-02-14 8 views
0

getData()関数でフェッチしたデータを返し、返された値(return this.getStreamer(values[0],values[1]);)を使用してStreamerContainerResultコンポーネントをレンダリングしようとしています。データをフェッチして特定の値を返す関数を作成したい

しかし、それは戻って保持します..「未定義」と、結果として、私は何をレンダリングカント

私は過去数時間のために、このバグに引っかかっていると私は自分でそれを把握するカント。

getData(value, type) { 
    let streamerData = []; 

    let urls = ['https://wind-bow.gomix.me/twitch-api/streams/' + value, 'https://wind-bow.gomix.me/twitch-api/users/' + value]; 

    const getJson = url => fetch(url).then(res => res.json()); 
    Promise.all(urls.map(getJson)) 
      .then((values) => { 
      if (type === "search") { 
       this.setState({ 
       streamer: values 
       }); 
       console.log("searching"); 
      } else { 
       console.log("displaying"); 
       return this.getStreamer(values[0],values[1]); 
      } 
      }).catch(err => { 
      console.log('Something went wrong...') 
      }); 
} 

https://codepen.io/brood915/pen/OWQpmy?editors=0110

答えて

0

あなたはasyncronousコールバック関数内からのデータを返すようにしようとしています。その結果、情報にアクセスすることはできません。下記のコールバックdoneの機能と参照番号thisのスニペットをご覧ください。乾杯。

//Notice I added a done callback for when our asyncronous function is finished 
function getData(value, type, done) { 
    //Added a variable that points to this (to have scope to our other functions) 
    var self = this; 

    let streamerData = []; 

    let urls = ['https://wind-bow.gomix.me/twitch-api/streams/' + value, 'https://wind-bow.gomix.me/twitch-api/users/' + value]; 

    const getJson = url => fetch(url).then(res => res.json()); 

    //Due to the asyncronous nature of a promise, you cannot return information via a return. See below... 
    Promise.all(urls.map(getJson)) 
    .then((values) => { 
     if (type === "search") { 
     self.setState({ 
      streamer: values 
     }); 
     console.log("searching"); 
     } else { 
     console.log("displaying"); 

     //This return is the return for the function, it won't return the data 
     // return self.getStreamer(values[0], values[1]); 
     //Return by passing the data to the callback 
     done(self.getStreamer(values[0], values[1])); 
     } 
    }).catch(err => { 
     console.log('Something went wrong...') 
    }); 
}; 

//Calling our function above. 
getData("<value>", "<type>", function(streamer) { 
    console.log(streamer); //This should contain the information you need. 
}) 

Hereは、コールバックを処理する方法については十分に理解しています。

+0

ありがとうございます。関数が返す要素に正常にアクセスしました。しかし、なんらかの理由で、まだコンポーネントによってレンダリングされません。なぜこれがですか? – brood915

+0

あなたは反応していますか?私はそれについて多くはわかりませんが、多分この[質問](http://stackoverflow.com/questions/24185029/reactjs-async-wait-for-results)が役立ちます。乾杯。 – matt

関連する問題