2016-12-19 63 views
0

我使用的是我的應用程序的狀態,但我發現很難正確更新它的狀態,當它嵌套。處理狀態更新對象

正如你可以看到我用的...狀態在我減速,但有沒有使用這個時候我只需要更新的子對象的關鍵,保持狀態的其餘的方法嗎?請參閱下面的例子

// 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 protected]', 
        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 
     }; 

回答

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);

+0

也發現了答案在這裏:https://github.com/reactjs/redux/issues/432 – NealVDV

0

在初始狀態,內容應該是{},而不是空。 然後,您可以使用Object.assign更改reducer中的狀態。

例如:

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