如何用 fetch api 正确替换 axios api 并在 nodeJS 中映射接收到的数据?
how to properly replace axios api with fetch api and map over the received data in nodeJS?
这是整个文件的 link - 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, users: [], error: '' }
{
loading: false,
users: [],
error: 'res.json(...).map is not a function'
}
我做错了什么?为什么我不能映射数据?
调用 res.json()
将 return 一个 Promise。您需要添加第二个 then 块:
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));
});
这是整个文件的 link - 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, users: [], error: '' }
{
loading: false,
users: [],
error: 'res.json(...).map is not a function'
}
我做错了什么?为什么我不能映射数据?
调用 res.json()
将 return 一个 Promise。您需要添加第二个 then 块:
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));
});