:
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.
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
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: –