如何在 redux 存储中保存数组对象数据

how to save array object data in redux store

我尝试在我的 React Native 应用程序的 redux store 中存储多个对象,但只有一个对象被保存, 我是 redux 的新手,我尝试了很多在 Whosebug 上找到的解决方案,但没有一个有效:/

我店里的结果:

"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(荨麻疹[i]) return :

 LOG  {"hive_id": 123, "hive_name": "HelloHive"}
 LOG  {"hive_id": 12944, "hive_name": null}

谢谢你

在你的减速器中试试这个:

case SET_HIVES:
      return {
        ...state,
        hives: [...state.hives,action.payload],
      };
    [...]

希望对您有所帮助。有问必答

首先,在你的 reducer 中你不需要使用 ...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));
      }
    });
  };
};

这样它会将整个数组写入 redux 中的那个变量。

您可以在下面尝试这个,这样您就可以存储整个数组。假设你已经有了行动。

初始状态

export default {
hives:[]
}

HivesReducer

export default function counter(state = initialState.hives, action) {
  switch (action.type) {
    case Types.SET_HIVES:
      return [...state, action.payload];
    default:
      return state;
  }
}