如何解决如何使用 fetch api 正确替换 axios api 并映射 nodeJS 中接收到的数据?
这是整个文件的链接 - asyncActions.js
带有axios api的部分-
const fetchUsers = () => {
return function (dispatch) {
dispatch(fetchUsersRrequest());
axios
.get("https://jsonplaceholder.typicode.com/users")
.then((res) => {
// res.data is the array of users
const users = res.data.map((user) => user.id);
dispatch(fetchUseRSSuccess(users));
})
.catch((error) => {
// error.message gives the description of message
dispatch(fetchUsersFaliure(error.message));
});
};
};
{ loading: true,users: [],error: '' }
{
loading: false,users: [
1,2,3,4,5,6,7,8,9,10
],error: ''
}
用fetch api替换部分-
const fetchUsers = () => {
return function (dispatch) {
dispatch(fetchUsersRrequest());
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => {
const users = res.json().map((user) => user.id);
console.log(users);
dispatch(fetchUseRSSuccess(users));
})
.catch((error) => {
dispatch(fetchUsersFaliure(error.message));
});
};
};
输出 -
{ loading: true,error: 'res.json(...).map is not a function'
}
我做错了什么?为什么我不能映射数据?
解决方法
调用 res.json()
将返回一个 Promise。您需要添加第二个然后阻止:
fetch("https://jsonplaceholder.typicode.com/users")
.then((res) => res.json())
.then((res) => {
const users = res.map((user) => user.id);
console.log(users);
dispatch(fetchUsersSuccess(users));
})
.catch((error) => {
dispatch(fetchUsersFaliure(error.message));
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。