2016-11-15 4 views
3

내 앱이로드 중임을 나타내는 회 전자가 있습니다. 내 애플 리케이션의 많은 감속기는이 로더를 true 또는 false로 설정할 수 있어야합니다.redux 저장소의 isLoading 필드 업데이트

내 가정 : 이 필드는 상태 트리의 최상위 레벨에 있어야합니다. isLoading이라고합시다.

문제점 : Redux 축소 기가 상태 트리의 자체 부분을 업데이트합니다. 가장 낮은 레벨의 isLoading 필드를 업데이트하기 위해 감속기를 구조 할 수있는 몇 가지 방법은 무엇입니까?

나는 redux-thunk에 익숙하지만 모든 행동에 이벤트를 파견하는 것이 과잉이라고 생각됩니다. 하지만 어쩌면 내가 틀렸어. 올바른 접근법이야. 또한 틀림없이 내 상태 트리를 디자인 할 가능성이 있습니다. 참고로

, 나는 현재 REDUX 같은 썽크 사용하고 있습니다 : 당신이 당신의 isLoading 감속기는 모든 관련 행동에 반응 할 수 있도록

export const fetchAssets =() => { 
    return dispatch => { 
    request 
     .get('http://myapi.com/assets') 
     .set('Accept', 'application/json') 
     .end(function(err, res){ 
     if (err) { 
      return dispatch(fetchAssetsFailure(err)); 
     } 
     dispatch(fetchAssetsSuccess(res.body.data)); 
     }); 
    } 
} 

답변

1

기어 대신이 값을 설정 다른 이경, 모든 파견 조치를받을 수 있습니다. 모든 관련 작업을 예측할 수 없기 때문에 분명히 action.type을 사용할 수 없으며 매우 귀찮은 감소 요인이됩니다. 당신이 할 수있는 것은 행동에 다른 필드를 추가하는 것이며,이 감속기는 그 필드에 반응 할 것입니다.

샘플 행동 작성자 :

const createSampleAction = (payload, isLoading) => ({ 
    type: 'SAMPLE_ACTION', 
    payload, 
    meta: { 
     isLoading 
    } 
}); 

그리고 감속기 :

const isLoadingReducer = (state = false, { meta }) => { 
    const isLoading = meta && meta.isLoading; 

    if (isLoading !== undefined) { 
     return isLoading; 
    } 

    return state; 
} 

대신 조치 유형의 메타를 사용하는 감속기 편안하지 않은 경우, 당신이 할 수있는 showLoading/hideLoading 작업을 전달하기 위해 동일한 속성을 수행 할 미들웨어를 만들고 감속기는 해당 작업에 응답합니다.

const isLoadingMiddleware = ({ dispatch }) => next => { 
    next(action); 
    const isLoading = action.meta && action.meta.isLoading; 

    if (isLoading !== undefined) { 
     dispatch(isLoading ? showLoading() : hideLoading()); 
    } 
}