2015-10-26 15 views
14

fetchPosts eylemini componentDidMount adresindeki bir Bileşen'den arayarak senkronize olmayan bir gönderi listesi alıyorum. İstek, ilgili redüktör (durumu güncelleyen) tarafından alındıktan ve ele alındığında, yeni alınan mesajların bir dizi ile birlikte başka bir eylemi fetchPostsMetaData çağırmak isterim.Redux'da birbirini izleyen ve bağımlı olan iki Async çağrısı nasıl kullanılır?

Ben redux-thunk yazılım kullanılması ve jQuery.ajax

bu konuda gitmek için en iyi yolu nedir kullanarak ajax istekleri yapıyorum? Googling'i denedim, ancak alakalı bir örnek/cevap bulamadı. redux-thunk kullanma

cevap

10

:

class PostIndex extends React.Component { 
    componentDidMount() { 
    const { dispatch } = this.props; 
    dispatch(getPosts()); 
    } 
    ... 
} 

function fetchPosts() { 
    return dispatch => { 
    fetchPostsAjax() 
     .then(res => { 
     dispatch({ type: 'RECEIVE_POSTS', payload: res }); 
     dispatch(fetchPostMeta(res)); 
     }) 
    } 
} 

function fetchPostMeta(posts) { 
    return dispatch => { 
    fetchPostMetaAjax(posts) 
     .then(res => dispatch({ type: 'RECEIVE_POST_META', payload: res })); 
    } 
    } 
} 

function fetchPostAjax() { 
    // return a promise, whether from jQuery.ajax or fetch 
} 

function fetchPostMetaAjax() { 
    // return a promise 
} 

Bu redux-thunk için oldukça standart kullanım durumdur. Yukarıdaki örnek soruyu soruyorsun yolu doğru kanat, ancak redux-thunk örnek Burada sağlanan görünen bir tek eylem yaratıcısı içinde bunu başarabilir: http://redux.js.org/docs/advanced/AsyncActions.html

nedir farklı benim örnekte ben olduğum ilk görev yerine doğrudan ikinci görev yapmak yerine, bir thunk içine bir thunk göndermek. Yani bu onun eşdeğeri: Eğer { type: RECEIVE_POSTS, payload: res } gibi bir eylem sevk zaman, senkron ve senden önce redüktör güncellemeler aşağıdaki zaman uyumsuz işlem sevk çünkü

function fetchPosts() { 
    return dispatch => { 
    fetchPostsAsync() 
     .then(res => { // res is posts 
     dispatch({ type: 'RECEIVE_POSTS', payload: res }); 
     return fetchPostMetaAsync(res); 
     }) 
     .then(res => { // res is metadata 
     dispatch({ type: 'RECEIVE_POST_META', payload: res }); 
     }) 
    } 
} 

herhangi yarış koşulları içine yayınlanmaz.

+0

Evet, bu mükemmel çalışıyor ve mantıklı geliyor. Teşekkürler! Bunu, jQuery'nin $ .ajax ({... başarı: function (result) {...}}) 'ile değiştirerek sağladığınız ikinci örnek gibi bitirdim. Ayrıca, ilk örneğinizde yinelenen 'fetchPosts()' çağrısı var, birincisini daha anlaşılır olması için 'getPosts()' olarak düzenlemek isteyebilirsiniz. Tekrar teşekkürler! – liorbrauer

+1

Bunu işaretlediğiniz için teşekkürler! Onu düzeltdim. İkinci örneğin daha aptalca olduğunu ve sözlerin çok eğlenceli olduğunu düşünüyorum: –

İlgili konular