[英]Data fetched from axios is storing inside an additional Array without a reason
I am fetching below data from mongo:我正在从 mongo 获取以下数据:
"data": [
{
"_id": "5ee3f064344d21fb2645f5c0",
"name": "John",
"surname": "Doe",
"email": "john@gmail.com",
"createdAt": "2020-06-12T21:15:16.624Z",
"__v": 0
},
{
"_id": "5ee5e27f1ecd8f05ad764057",
"name": "Jane",
"surname": "Doe",
"email": "jane@gmail.com",
"createdAt": "2020-06-14T08:40:31.701Z",
"__v": 0
}
I am using axios to fetch the data.我正在使用 axios 来获取数据。 Below is my code that is fetching the data:
下面是我获取数据的代码:
async function getUser() {
const user = await axios.get('/api/plugins/users');
dispatch({
type: 'GET_USER',
payload: user.data.data,
});
}
Data is all good, but the problem is that I am getting the data Array inside another Array and I am not sure how.数据都很好,但问题是我在另一个数组中获取数据数组,我不知道如何。
Here is what I am getting:这是我得到的:
[
[
{"_id":"5ee3f064344d21fb2645f5c0","name":"John","surname":"Doe","email":"john@gmail.com","createdAt":"2020-06-12T21:15:16.624Z","__v":0},
{"_id":"5ee5e27f1ecd8f05ad764057","name":"Jane","surname":"Doe","email":"jane@gmail.com","createdAt":"2020-06-14T08:40:31.701Z","__v":0}
]
]
This is my Initial State and reducer, both are in separate files:这是我的初始 State 和减速器,两者都在单独的文件中:
const initialState = {
users: [],
loading: true,
};
case 'GET_USER':
return {
...state,
users: [...state.users, action.payload],
loading: false,
};
This seems very odd to me and I am not sure what is causing it to put the data inside another array.这对我来说似乎很奇怪,我不确定是什么导致它将数据放入另一个数组中。 Can someone please take a look.
有人可以看看吗。
action.payload
is an array. action.payload
是一个数组。 state merging is wrong in state 合并错误
case 'GET_USER':
return {
...state,
users: [...state.users, action.payload], //it's wrong.It will create nested array
loading: false,
};
it should be它应该是
users: [...state.users, ...action.payload], // spread array element in users
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.