简体   繁体   English

具有依赖关系的多次调用 redux-thunk

[英]Multiple calls with dependencies redux-thunk

Question:题:

I use redux-thunk and I want to receive posts.我使用redux-thunk并且我想接收帖子。 To receive posts I need to get users.要接收帖子,我需要获得用户。 So I have doubts about my thunk, Is it right to get all the data in one thunk, if not how to split it into two thunks?所以我对我的 thunk 有疑问,在一个 thunk 中获取所有数据是否正确,如果不是如何将其拆分为两个 thunk?

Thunk example: Thunk 示例:

export default group_id => {
  return async dispatch => {
    const users = await API.get(`/users?group_id=${group_id}`) // get users
    const posts = await axios.all([...getPosts(users)]) // get all posts by user ids
    dispatch(loadUsersAction(users))
    dispatch(loadPostsAction(posts))
  }
}

There might be several approaches depending of your requirements.根据您的要求,可能有多种方法。

If the purpose is to load, initially users, and then their post, i would call firstly /users , and then dispatch another action creator to get their /posts .如果目的是首先加载用户,然后加载他们的帖子,我会首先调用/users ,然后派遣另一个动作创建者来获取他们的/posts Because getting it all together would make your users waiting longer for something to change in the UI (ex: loading spinner), thus i would split these in two separate actions.因为将它们放在一起会使您的用户等待更长时间来等待 UI 中的某些更改(例如:加载微调器),因此我会将它们拆分为两个单独的操作。

 export function getUsers(group_id) => { return async dispatch => { const users = await API.get(`/users?group_id=${group_id}`); dispatch(loadUsersAction(users)); return users; }; }; export function getPostForGroupUsers (group_id) => { return async dispatch => { const users = await dispatch(getUsers(group_id)); const posts = await axios.all([...getPosts(users)]); dispatch(loadPostsAction(posts)); return posts; } } // or just call users, dispatch and get them from store export function getPostForAllUsers () => { return async dispatch => { // this depends on your implementation const users = getFromReduxStore('users'); const posts = await axios.all([...getPosts(users)]); dispatch(loadPostsAction(posts)); return posts; } }

Maybe you can provide more details of your case, I then could give more precise response.也许您可以提供更多关于您的案例的详细信息,然后我可以给出更准确的答复。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM