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

前端 未结 4 777
予麋鹿
予麋鹿 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
         }
    }
    

提交回复
热议问题