简体   繁体   English

如何更改 react-redux 中的 initialState

[英]how to change initialState in react-redux

I'm using react-redux to fetch data from MongoDB database and put it into React App.我正在使用 react-redux 从 MongoDB 数据库中获取数据并将其放入 React App。
I've following structure to work upon:我有以下工作结构:

const initialState = {
  Level: [{
    wId: Math.random(),
    Level1: [
      {
       id: Math.random(),
       item1: 'item1',
       item2: 'item2'
      },
      .......
    ],
    Level2: [
      {
       id: Math.random(),
       item1: 'item1',
       item2: 'item2'
      },
      .......
    ]
  }]
}

Redux Function: Redux Function:

export default function (state = initialState, action) {
  switch (action.type) {
    case GET_ITEMS:
      return {
        ...state,
        // what should i write here to get above mentioned state structure
      }
   ..............
}

Note:笔记:

  1. Initially Level is empty.最初Level是空的。 So if new data is received in payload then the following structure should be formed.因此,如果在有效载荷中接收到新数据,则应形成以下结构。
  2. How to update particular item like item1 at level2如何在level2更新特定item ,如item1

Sample Input:示例输入:

action.payload = {
    id1: 23234,             // should be assigned in Wid
    ITEM: [                 // Level1
        {
            id2: 89724,       // should be assigned in Level1.id
            i: 'abc',       // should be assigned in Level1.item1
            j: 'xyz'        // should be assigned in Level1.item2
        }
    ]
}

I you dont know how many items you are going to get its would be difficult.我不知道您要获得多少物品会很困难。 One way to work around this issue could compare the previos state with current state and update only necessary part that got changed.解决此问题的一种方法是将以前的 state 与当前的 state 进行比较,并仅更新已更改的必要部分。

You can use number of libraries or follow any answer in How to determine equality for two JavaScript objects?您可以使用库的数量或遵循如何确定两个 JavaScript 对象的相等性? to compare the objects.来比较对象。

Ideally you would need different actions to update Level, Level ->Level 1 and so on.理想情况下,您需要不同的操作来更新 Level、Level ->Level 1 等等。

Create separate actions for adding levels.为添加级别创建单独的操作。 Call that action when on user events which add a level to your initial state.在发生用户事件时调用该操作,将级别添加到您的初始 state。

export default function (state = initialState, action) {
  switch (action.type) {
    case GET_ITEMS:
      return {
        ...state,
        // what should i write here to get above mentioned state structure
      }
   case ADD_LEVELS:
      return {
                ...state,
                Level: [...state.Level, action.payload.Level]
             }
}

You can move the id generation logic to the component as it will make your life simpler.您可以将 id 生成逻辑移动到组件中,因为它会让您的生活更简单。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM