我尝试返回由函数getData()获取的数据,并使用返回值(return this.getStreamer(values[0],values[1]);)呈现StreamerContainerResult组件。
但是,它一直返回"undefined“,因此,我无法呈现任何内容。
在过去的几个小时里,我被这个bug卡住了,我自己也搞不清楚。
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...')
});
} 发布于 2017-02-15 06:24:10
您正在尝试从异步回调函数中返回数据。因此,这些信息将无法访问。下面是带有回调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是一些关于如何使用回调的好读物。
https://stackoverflow.com/questions/42237267
复制相似问题