用axios链接redux有效载荷

时间:2017-07-10 22:52:56

标签: reactjs redux redux-thunk redux-promise-middleware

我正在使用React和Redux(带有承诺中间件和thunk)构建一个前端,用于WordPress后端(REST)。

现在我正在使用Redux进行简单的调度以获取页面数据,例如这样:

export const fetchPostBySlug = (slug) => {
  return {
    type: "FETCH_MODULES",
    payload: axios.get(`${REST_URL}/wp/v2/posts?slug=${slug}`)
  }
}

现在我想做一个更复杂的电话。我想从WordPress中获取所有标签并返回这些标签。然后我获取所有特色标签。然后我获取所有具有精选标签的帖子。然后我获取所有具有精选标记的自定义帖子类型。

我的有效载荷最终看起来像这样:

payload: {
  id: 5,
  name: 'tag_5',
  slug: '/tag_5',
  tags: [all tags]
  posts: [all posts and cpt having a featured tag in here together]
}

这就是我现在拥有的东西,它基本上取出了所有内容但却没有连接和发送。

const fetchTagPosts = () => {
  axios.all([fetchAllTags(), fetchFeaturedTopics()])
    .then(axios.spread((all, featured) => {
      let payload = {}
      const ft = featured.data.featured_tags
      const ft_length = ft.length

      ft.map((x, i) => {
        getPostsByTag(x.term_id).then(y => payload = addPostToPayload(y.data, x.term_id, payload))
        getCPTByTag(x.term_id).then(y => payload = addPostToPayload(y.data, x.term_id, payload))
        // I need to check here if both are loaded, so I can concat the arrays
        if (ft_length === i + 1) {
          // I need to dispatch/return the payload here
        }
      })
    }))
}

const addPostToPayload = (p, id, payload) => {
  return {
    [id]: {
      posts: payload[id] ? payload[id].posts.concat(p) : p
    }
  }
}

1 个答案:

答案 0 :(得分:1)

由于您正在使用thunk,因此可以返回一个接受调度的函数,并使用该调度将有效负载发送到reducer。

你也不需要map函数中的if语句,因为map不会遍历数组。实际上,在这种情况下使用forEach会更合适,因为我们没有返回任何内容。

所以你的fetchTagPosts看起来如下:

const fetchTagPosts = (dispatch) => {
  axios.all([fetchAllTags(), fetchFeaturedTopics()])
    .then(axios.spread((all, featured) => {
      let payload = {}
      const ft = featured.data.featured_tags
      
      // loop through ft
      ft.forEach(x => {
        getPostsByTag(x.term_id).then(y => payload = addPostToPayload(y.data, x.term_id, payload))
        getCPTByTag(x.term_id).then(y => payload = addPostToPayload(y.data, x.term_id, payload))
      });
      
      // dispatch payload to reducer
      dispatch({
        type: 'FETCH_TAG_POSTS',
        payload,
      });
    }))
}