2017-09-29 1 views
1

첫 호출이 isLoading 상태를 업데이트하는 Redux에서 동기식 디스패치 호출을 시도하고 UI에 로딩 아이콘을 표시 한 다음 두 번째 호출이 백그라운드에서 많은 동기식 계산을 수행하도록합니다. 항목 위치 업데이트 - 2-5 초 정도 걸립니다.동기식 Redux 작업

첫 번째 동작이 발생하고 상태가 올바르게 변경되었지만 그 직후에는 반응 프런트 엔드 구성 요소에 충돌하지 않지만 두 번째 디스패치로 이동합니다. 그것은 첫 번째 디스패치 후에 짧은 timeout을 추가 할 때 작동하지만 고정 된 대기 시간을 하드 코드하는 것은 싫다.

이 문제에 대한 해결책이 더 있습니까? 작동하지

:

const showLoadingIcon =() => ({type: types.SHOW_LOADING_ICON}); 
export const updateInteractionTypeScores = (updatedValues) => dispatch => { 
    dispatch(showLoadingIcon()); 
    dispatch({type: types.UPDATE_VALUES, updatedValues}); 
}; 

WORKING : 당신이 동기 동작이 정말 특정 시간에 상점의 업데이트, 비동기 작업을입니다 부르는

const showLoadingIcon =() => ({type: types.SHOW_LOADING_ICON}); 
export const updateInteractionTypeScores = (updatedValues) => dispatch => { 
    dispatch(showLoadingIcon()); 
    setTimeout(() => dispatch({type: types.UPDATE_VALUES, updatedValues}), 100); 
}; 

답변

1

. 이와 같은 일반적인 패턴은 액션의 각 상태에 대해 (최소한) 세 개의 디스패치를 ​​갖는 것입니다.

  1. 비동기 작업이 시작됩니다
  2. 비동기 작업은
  3. 비동기 작업은 비동기 작업이 상점을 업데이트하는 "ASYNC_ACTION_LAUNCHED"액션, 귀하의 구성 요소가 올바르게 있습니다하기를 전달 시작

실패 성공 연결된 (맞습니까?) 따라서로드 아이콘이 표시됩니다.

성공하면 "ASYNC_ACTION_SUCCESS"가 전달되고 저장소가 업데이트되며 구성 요소가 새 저장소 내용으로 다시 전달됩니다.

"ASYNC_ACTION_FAILURE"가 전달되면 저장소가 업데이트되고 구성 요소는 빈 내용으로 다시 렌더링되며 오류 메시지가 표시됩니다. 실제로

, 이것은 더 많은 코드 금액, 그러나 이것은 훨씬 더 많은 가능성을 허용 :

const asyncActionLaunched =() => ({type: types.ASYNC_ACTION_STARTED}); 
const asyncActionSuccess =() => ({type: types.ASYNC_ACTION_SUCCESS}); 
const asyncActionFailed =() => ({type: types.ASYNC_ACTION_FAILED}); 

export const updateInteractionTypes = dispatch => { 
    dispatch(asyncActionLaunched()); 

    // I don't know your setup 
    // But this whould either be a Promise, or return a boolean 

    // in the case of a synchronous function 
    const result = makeSynchronousCalculations(); 
    if (result) { 
     dispatch(asyncActionSuccess()); 
     // dispatch another action that updates store 
    } else { 
     dispatch(asyncActionFailed()); 
     // dispatch another action that updates store 
    } 
    // in the case of a promise 
    asyncBlockingAction() 
     .then(
      dispatch(asyncActionSuccess()); 
      // dispatch another action that updates store 
     ).catch(
      dispatch(asyncActionFailed()); 
      // dispatch another action that updates store 
     ); 
}; 
+1

아, 완전한 의미가 잘 작동합니다 ... 감사합니다! – hotshotiguana

관련 문제