How do I add an element to array in reducer of React native redux?

前端 未结 4 721
予麋鹿
予麋鹿 2020-12-22 16:52

How do I add elements in my array arr[] of redux state in reducer? I am doing this-

import {ADD_ITEM} from \'../Actions/UserActions\'
const ini         


        
相关标签:
4条回答
  • 2020-12-22 17:18

    push does not return the array, but the length of it (docs), so what you are doing is replacing the array with its length, losing the only reference to it that you had. Try this:

    import {ADD_ITEM} from '../Actions/UserActions'
    const initialUserState = {
    
        arr:[]
    }
    
    export default function userState(state = initialUserState, action){
         console.log(arr);
         switch (action.type){
            case ADD_ITEM :
              return { 
                 ...state,
                 arr:[...state.arr, action.newItem]
            }
    
            default:return state
         }
    }
    
    0 讨论(0)
  • 2020-12-22 17:24

    If you need to insert into a specific position in the array, you can do this:

    case ADD_ITEM :
        return { 
            ...state,
            arr: [
                ...state.arr.slice(0, action.pos),
                action.newItem,
                ...state.arr.slice(action.pos),
            ],
        }
    
    0 讨论(0)
  • 2020-12-22 17:32

    I have a sample

    import * as types from '../../helpers/ActionTypes';
    
    var initialState = {
      changedValues: {}
    };
    const quickEdit = (state = initialState, action) => {
    
      switch (action.type) {
    
        case types.PRODUCT_QUICKEDIT:
          {
            const item = action.item;
            const changedValues = {
              ...state.changedValues,
              [item.id]: item,
            };
    
            return {
              ...state,
              loading: true,
              changedValues: changedValues,
            };
          }
        default:
          {
            return state;
          }
      }
    };
    
    export default quickEdit;
    
    0 讨论(0)
  • 2020-12-22 17:40

    Two different options to add item to an array without mutation

    case ADD_ITEM :
        return { 
            ...state,
            arr: [...state.arr, action.newItem]
        }
    

    OR

    case ADD_ITEM :
        return { 
            ...state,
            arr: state.arr.concat(action.newItem)
        }
    
    0 讨论(0)
提交回复
热议问题