2016-12-19 25 views
0

私はアプリケーションの状態にreduxを使用していますが、ネストされているときに状態を正しく更新するのは難しいと感じています。ハンドル状態更新オブジェクト

私のレデューサーでは...状態を使用していますが、子オブジェクトのキーを更新して残りの状態を維持する必要がある場合には、これを使用する方法がありますか?あなたがObject.assign()

この例を試すことができます例えば、以下を参照してください

// 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

は、使用方法を示しています。あなたも同じ広がりオペレータあなたの初期状態では...

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

。また、ここで答えを見つけました – NealVDV

0

を使用することができます

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

、コンテンツがnullの代わり{}でなければなりません。 次に、減速機の状態をObject.assignで変更することができます。

例:https://github.com/reactjs/redux/issues/432:

case RECEIVE_USER: 
    return{ 
    ...state, 
    content: Object.assign({}, state.content, { 
     key: 'thing I only want to update' 
    } 
関連する問題