【发布时间】:2020-05-12 17:25:27
【问题描述】:
我尝试在我的 react native 应用程序的 redux 存储中存储多个对象,但只有一个对象被保存, 我是 redux 的新手,我尝试了很多在 StackOverflow 上找到的解决方案,但没有一个有效:/
结果我在我的商店:
"hives": {"hive_id": 12944, "hive_name": null}
我想要的结果(或类似的):
"hives": [
1: {"hive_id": 123, "hive_name": "HelloHive"},
2: {"hive_id": 12944, "hive_name": null}]
商店:
const middleware = [thunk]
export const store = createStore(persistedReducer, applyMiddleware(...middleware));
export const persistor = persistStore(store);
减速器:
const INIT_STATE = {
hives: [],
}
const hiveReducer = (state = INIT_STATE, action) => {
switch (action.type) {
case SET_HIVES:
return {
...state,
hives: action.payload,
};
[...]
动作创建者:
export const setHives = hives => {
return {
type: SET_HIVES,
payload: 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') {
for (let i = 0; i < hives.length; i++) {
console.log(hives[i]);
dispatch(setHives(hives[i]));
}
}
});
};
};
我的 API 发给我:
"hives": [
{
"hive_id": 123,
"hive_name": "HelloHive"
},
{
"hive_id": 12944,
"hive_name": null
}
]
和 console.log(hives[i]) 返回:
LOG {"hive_id": 123, "hive_name": "HelloHive"}
LOG {"hive_id": 12944, "hive_name": null}
谢谢你
【问题讨论】:
-
for 循环中不必要的调度 - 调度所有配置单元
-
hives: [...state.hives, action.payload],不应该吗?
标签: reactjs react-native redux react-redux redux-thunk