如何在react redux中存储多层物体?

时间:2017-06-07 22:52:26

标签: javascript reactjs object redux

我正在尝试将多个对象添加到desire的对象中,并存储在此对象内收集的所有需求。我正在尝试将密钥设置为它所设置的日期,因此每条记录都有一个单独的密钥。

然而,所有这一切都发生了,我最终在状态中有一个desire对象,每次写入都会被覆盖,每次更新都会删除sexmasturbation

我知道我应该能够得到这个,但是它已经迟到了,我被困住了:D

减速

import Moment from 'moment';
import {
  SET_DESIRE_DATA,
  SET_MASTURBATION_DATA,
  SET_SEX_DATA
} from '../actions/dataAction';

const initialState = {
  'desire': {},
    'masturbation': {},
    'sex': {}
};

function desire (state = initialState, action) {
    //var action
    //{
    //    desire: 3, 
    //    date: Wed Jun 07 2017 23:45:41 GMT+0100 (BST)
    //}
    switch (action.type) {
        case SET_DESIRE_DATA:
            //Date returned 07_06_2017
            //Moment(action.data.date).format('D-MM-YYYY')
            return {
                ...state.desire,
                desire: action.data
            }
        case SET_MASTURBATION_DATA:
            return {
                ...state,
                masturbation: action.data
            }
        case SET_SEX_DATA:
            return {
                ...state,
                sex: action.data
            }
    }
    return state
}

export default desire;

更新了Store.desire

enter image description here

1 个答案:

答案 0 :(得分:0)

试试这个:

function desire (state = initialState, action) {
    //var action
    //{
    //    desire: 3, 
    //    date: Wed Jun 07 2017 23:45:41 GMT+0100 (BST)
    //}
    switch (action.type) {
        case SET_DESIRE_DATA:
            //Date returned 07_06_2017
            const key = Moment(action.data.date).format('D-MM-YYYY')
            const desire = Object.assign({}, state.desire);
            desire[key] = action.data
            return {
                ...state.desire,
                desire,
            }
        case SET_MASTURBATION_DATA:
          //similar code here
    }
    return state
}

export default desire;