在从 API 获取响应的简单 React 应用程序中,以下带有大括号的代码的结果数据值为undefined。
fetch('http://localhost:8000/track/?id='+this.state.input)
.then(res => {res.json()}) //Note Curly braces around {res.json()}
.then((data) => {
console.log(data);
Run Code Online (Sandbox Code Playgroud)
然而,当花括号被删除时,令人惊讶的是它在控制台中获取并打印了响应数据。
fetch('http://localhost:8000/track/?id='+this.state.input)
.then(res => res.json()) //No Curly braces - then works fine
.then((data) => {
console.log(data);
Run Code Online (Sandbox Code Playgroud)
Promise 函数周围有大括号的这种行为的原因是什么?是不是不能使用大括号?为什么?不过 Promise 有点令人困惑。