Javascript获取和console.log json给出了未定义

时间:2018-07-02 15:54:48

标签: javascript ecmascript-6 fetch

html的内部正文::

<button class="getUsers">get users</button>

JS ::

const getUsers = () = > {
  fetch("users.json")
    .then((res) = > {
      res.json()
    })
    .then((data) = > {
      console.log(data);
    })
}
document.querySelector(".getUsers").addEventListener("click", getUsers)

users.json ::

[{
  "id": 1,
  "name": "Rick",
  "email": "rick@gmail.com"
}, {
  "id": 2,
  "name": "maria",
  "email": "maria@gmail.com"
}, {
  "id": 3,
  "name": "gadnjaman",
  "email": "gadnjaman@gmail.com"
}]

我的问题是,为什么在单击按钮时会出现未定义的状态,我该如何解决?

2 个答案:

答案 0 :(得分:1)

您需要在此处返回json()

const getUsers = () = > {
  fetch("users.json")
    .then(res => res.json())
    .then(data => console.log(data));
}

这里:

res => res.json()
// equivalent to: (res) => { return res.json(); }

或者您可以像这样使用async / await:

const getUsers = async () => {
  const res = await fetch("users.json");
  const data = await res.json();
  console.log(data);
}

演示:

const getUsers = async () => {
  const res = await fetch("https://jsonplaceholder.typicode.com/users");
  const data = await res.json();
  console.log(data);
}

getUsers();

答案 1 :(得分:1)

Arrow functions MDN web doc中所述:

  

箭头功能可以具有“简洁主体”或通常的“块”   身体”。

     

在简洁的正文中,仅指定一个表达式,该表达式成为   显式返回值。在块体中,必须使用显式   返回声明。

因此,如评论中所述,(块体):

.then((res) = > {
  return res.json()
})

或(简洁的正文):

.then(res => res.json())