所以这个问题非常简单。为什么这有效:
fetch("https://api.github.com/users/vampaynani/repos")
.then((res) => res.json())
.then((repos) => {
console.log(repos);
this.setState({ repos });
});
但这并不:
fetch("https://api.github.com/users/vampaynani/repos").then((repos) => {
var r = repos.json();
this.setState({ repos: r });
});
这是它的沙箱链接:SandBox
也许我的理解是错误的,但在我看来,这些看起来都在做同样的事情。
最佳答案
这是因为 repos.json()
是一个需要之前解决(等待)的 promise 。
fetch("https://api.github.com/users/vampaynani/repos").then(async (repos) => {
var r = await repos.json();
this.setState({ repos: r });
});
关于javascript - 为什么 .then() 没有返回 JavaScript 获取所需的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73556955/