Lau*_*yne 5 reactjs react-native redux redux-thunk react-redux
我尝试在我的本机应用程序的 redux 商店中存储多个对象,但只有一个对象被保存,我是 redux 的新手,我尝试了在 StackOverflow 上找到的很多解决方案,但没有一个有效:/
结果我在我的商店:
"hives": {"hive_id": 12944, "hive_name": null}
Run Code Online (Sandbox Code Playgroud)
我想要的结果(或类似的东西):
"hives": [
1: {"hive_id": 123, "hive_name": "HelloHive"},
2: {"hive_id": 12944, "hive_name": null}]
Run Code Online (Sandbox Code Playgroud)
店铺:
const middleware = [thunk]
export const store = createStore(persistedReducer, applyMiddleware(...middleware));
export const persistor = persistStore(store);
Run Code Online (Sandbox Code Playgroud)
减速机:
const INIT_STATE = {
hives: [],
}
const hiveReducer = (state = INIT_STATE, action) => {
switch (action.type) {
case SET_HIVES:
return {
...state,
hives: action.payload,
};
[...]
Run Code Online (Sandbox Code Playgroud)
动作创建者:
export const setHives = hives => {
return {
type: SET_HIVES,
payload: hives,
};
};
Run Code Online (Sandbox Code Playgroud)
行动:
export const getHives = () => {
return dispatch => {
axios.get(GET_HIVE_URL, HEADER).then(res => {
const status = res.data.status;
const hives = res.data.hives;
if (status == 'hiveFound') {
for (let i = 0; i < hives.length; i++) {
console.log(hives[i]);
dispatch(setHives(hives[i]));
}
}
});
};
};
Run Code Online (Sandbox Code Playgroud)
我的 API 发给我:
"hives": [
{
"hive_id": 123,
"hive_name": "HelloHive"
},
{
"hive_id": 12944,
"hive_name": null
}
]
Run Code Online (Sandbox Code Playgroud)
和 console.log(hives[i]) 返回:
LOG {"hive_id": 123, "hive_name": "HelloHive"}
LOG {"hive_id": 12944, "hive_name": null}
Run Code Online (Sandbox Code Playgroud)
感谢您
小智 5
首先,在您的减速器中,您不需要使用...state扩展运算符,因为 hives 似乎是您所在状态中唯一的一个变量。其次,您正在迭代配置单元的每个元素,因此您将逐一输入它们,从而覆盖前一个元素。您没有将其附加到数组中。以下是您需要更改操作的方法:
export const getHives = () => {
return dispatch => {
axios.get(GET_HIVE_URL, HEADER).then(res => {
const status = res.data.status;
const hives = res.data.hives;
if (status == 'hiveFound') {
dispatch(setHives(hives));
}
});
};
};
Run Code Online (Sandbox Code Playgroud)
这样它就会将整个数组写入 redux 中的该变量中。