处理状态更新对象

时间:2016-12-19 14:36:24

标签: javascript redux

我正在使用redux作为我的应用程序的状态,但我发现在嵌套时很难正确更新状态。

正如你所看到的,我在reducer中使用了...状态,但是当我只需要更新子对象的一个​​键并保持状态的其余部分时,有没有办法使用它?见下面的例子

// initial state
state = {
    isFetching: true,
    isUpdating: false,
    content: {
        key: 'content',
        otherkey: 'content' // Keep this one
    }
}

// returned new state
{
    ...state,
    content: {
        key: 'thing I only want to update'
    }
}

操作

export function requestUser() {
    return  {
        type: REQUEST_USER
    };
}

export function receiveUser(data) {
    return {
        type: RECEIVE_USER,
        payload: data
    };
}

export function fetchUser(userhash) {  
    return function (dispatch) {
        dispatch(requestUser);  

        return new Promise(resolve => setTimeout(resolve, 500)).then(() => {
            const data = {
                status: 200,
                data: {
                    firstName: 'Neal',
                    lastName: 'Van der Valk',
                    email: 'email@outlook.com', 
                    hash: 'zea7744e47747851',
                    permissions: {
                        'admin': true,
                        'results': true,
                        'database': true,
                        'download': true,
                        'property': true,
                        'departments': true,
                        'users': true,
                        'devices': true,    
                        'integrations': true,
                    },
                    notifications: {
                        'daily': true,
                        'weekly': false
                    }
                }
            };

            dispatch(receiveUser(data));
        });
    };
}

减速

const INITIAL_STATE = {
    isFetching: true,
    isUpdating: false,
    content: null
};

export default function(state = INITIAL_STATE, action) {
    switch (action.type) {
    case REQUEST_USER:
        return {
            ...state, 
            isFetching: true
        };

    case RECEIVE_USER:
        return {
            ...state, 
            isFetching: false,
            content: action.payload.data
        };

2 个答案:

答案 0 :(得分:1)

您可以尝试Object.assign()

此示例显示用法。

{
    ...state,
    content: Object.assign({}, state.content, { 
        key: 'thing I only want to update'
    }
}

您也可以使用相同的点差运算符...

    var state = {
        isFetching: true,
        isUpdating: false,
        content: {
            key: 'content',
            otherkey: 'content' // Keep this one
        }
    };

    var newState = {
       ...state,
       content: { 
         ...state.content, 
         key: 'thing I only want to update'
       }
    }
    console.log(newState);

答案 1 :(得分:0)

在初始状态下,内容应为{}而不是null。 然后,您可以使用Object.assign更改reducer中的状态。

示例:

case RECEIVE_USER:
  return{
    ...state,
    content: Object.assign({}, state.content, { 
      key: 'thing I only want to update'
  }