这可能是最简单的事情,但是下面的控制台日志无法查看api结果,任何人都可以看到原因,我是React BTW的新手。
componentDidMount() {
this.setState({ loading: true })
console.log('app mounted');
fetch('https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=8')
.then(data => data.json())
.then(data => this.setState({ data: data.articles, loading: false}))
console.log('Results -', JSON.stringify(this.data));
}
答案 0 :(得分:1)
您可以将结果记录在setState
函数的回调中,如下所示:
this.setState({ data: data.articles, loading: false}, () => console.log(data.articles))
答案 1 :(得分:0)
因此,您首先需要了解的是,您正在与Promises
一起工作。承诺是asynchronous
,这意味着您是否要编写这些代码行
let a = "a"
fetch('https://newsapi.org/...')
.then(() => { a = "b"; }
console.log(a) // "a"
结果将为a
,因为JavaScript会开始创建Promise
的任何情况(在这种情况下为fetch
),然后继续执行此行(在此情况下为{{ 1}})。 console.log(a)
部分将在诺言完成后执行,在您的情况下,等待网络流量返回。
那么您的情况是
.then
这里的第二件事是您正在登录// You set the state
this.setState({ loading: true })
// You log
console.log('app mounted');
// You create a promise
fetch('https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=8')
// all of these then things will be called when the network traffic finishes
.then(data => data.json())
.then(data => this.setState({ data: data.articles, loading: false}))
// this line is not part of the then so this is what actually gets called next
// so here you are still logging the original state of this.data not the one after the network traffic
console.log('Results -', JSON.stringify(this.data));
// some time in the future your thens will be executed
。您实际上要登录this.data
。所以你的代码应该像这样
this.state.data
答案 2 :(得分:0)
即使在返回数据之前,您的for (Uri uri : files) {
storageRef.child("PostData/" + UUID.randomUUID().toString()).putFile(uri).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
@Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
builder.setContentText("Upload Completed").setProgress(0, 0, false).setOngoing(false);
notificationManager.notify(NOTIFICATION_ID, builder.build());
Task<Uri> uri = taskSnapshot.getStorage().getDownloadUrl().addOnCompleteListener(new OnCompleteListener<Uri>() {
@Override
public void onComplete(@NonNull Task<Uri> task) {
Uri uri = task.getResult();
i[0]++;
if (i[0] == 1) {
mVideoUri = uri.toString();
Log.d("Log", "Video: " + mVideoUri);
} else {
mThumbUri = uri.toString();
Log.d("Log", "Thumbnail: " + mThumbUri);
}
}
});
}
});
仍在执行。
因此要控制台记录结果:
将console.log用作setState的回调,因为它是一个异步函数:
console.log('Results -', JSON.stringify(this.data));