2016-12-28 5 views
4

나는 async await을 지원하는 TypeScript 2.1과 함께 작업을 보내려면 redux-actionsredux-promise-middleware을 사용합니다.chaining redux-actions 및 redux-promise-middleware

이 모두 redux-actionsredux-promise-middleware

// create an async action 
const fooAction = createAction('FOO', async() => { 
    const { response } = await asyncFoo(); 
    return response; 
}); 

// use async action 
fooAction('123') 

를 사용하여 작업입니다 그리고 이것은 단지 redux-promise-middleware

const foo =() => dispatch => { 
    return dispatch({ 
    type: 'TYPE', 
    payload: new Promise() 
    }) 
    .then(() => dispatch(bar())); 
} 

어떻게 체인 redux-promise-middleware에서이 redux-actions와 함께 사용할 수 있습니다 사용, 액션 체인의 예입니다?

+0

, 나는 REDUX-사가로 전환. redux-thunk의 문제점은 액션에 매개 변수로서 점점 더 많은 데이터를 전송해야하고, 결국에는 애플리케이션의 전체 상태를 거기로 옮기고 싶다는 것입니다. Redux-saga는 기본적으로 이것을 알고 있으며 이것과 다른 유용한 것들을위한 특별한 방법을 가지고 있습니다. –

답변

3

당신이 경우에도 async await 동기 보이는 명심해야한다, 그것은 후드 약속을 사용하고 await 여부를 사용할 경우 async 기능은 항상 약속에 상관없이 반환됩니다.

createAction의 두 번째 매개 변수가 페이로드 작성자이므로 아무 것도 결과 개체를 사용하지 못하게 할 수 있습니다.

const fakeCall =() => new Promise(resolve => { 
    setTimeout(() => resolve({ response: 'ok' }), 1E3) 
}) 

const fooAction = createAction('FOO', async() => { 
    const { response } = await fakeCall() 
    return response 
}) 

const foo =() => dispatch => 
    dispatch(fooAction()) 
    .then(() => dispatch(bar())) 

// or 

const foo =() => async dispatch => { 
    await dispatch(fooAction()) 
    dispatch(bar()) 
} 
0

붙여주십시오 응답의 문제는 이벤트 루프를 차단하는 것입니다 "기다리고 있습니다"당신이 직접 약속을 처리해야한다는 것입니다 : 여기

은 초기 코드를 기반으로 한 예입니다.

"redux-promise-middleware"대신 redux-auto과 같은 API를 redux-promise-middleware와 함께 사용할 수 있지만 축소 기 호출을 연결하는 메커니즘도 제공됩니다.

// UI code 
actions.data.foo() 

// store/data/foo.js 
export function fulfillment(data,payload){ 
    return data 
} fulfillment.chain = actions.x.bar 

export function action(payload){ 
    return Promise.resolve() 
} 

은 정말, 그게 전부 :

귀하의 예는 같을 것이다. 액션을 체인 속성에 지정하면 redux-lifecycle의 오른쪽 지점에서 호출됩니다.

위의 소스를 이해하려면 다음을 수행하십시오. redux-auto는 자동으로 작업을 만들고 파일 구조에 따라 줄을 줄입니다. 여기서 폴더 이름은 상태에있는 속성의 이름이됩니다. 폴더 내의 파일은 해당 부분에서 수행 할 작업입니다.

는 여기에 실제 프로젝트에서이를 사용하여 5 달 후에 문서 chaining action together

+0

귀하의 답변에 광고를 게재 할 때 redux-auto는 귀하의 도서관임을 공개해야합니다. –