操纵Redux输出

时间:2017-04-29 18:21:07

标签: reactjs redux react-redux redux-thunk

我正在使用React应用程序使用WordPress Rest API,Redux和Thunk呈现WordPress网站的内容。

WordPress API会返回没有关于类别(nameslug等)的详细信息的帖子。我得到的只是id。我目前正在调用其他操作/功能来获取详细的类别信息(output)。以下是我目前如何获取帖子的示例。

// Actions.js

import axios from 'axios'

export const fetchPosts = (page = 1) => {
  return {
    type: "FETCH_POSTS",
    payload: axios.get(`${REST_URL}/wp/v2/posts?per_page=14&page=${page}`)
  }
}

|

// PostsReducer.js
const initialState = {
  posts: [],
  fetching: false,
  fetched: false,
  error: null
}

export default function reducer(state=initialState, action) {
  switch (action.type) {
    case "FETCH_POSTS": {
      return {
        ...state, 
        fetching: true
      }
    }
    case "FETCH_POSTS_REJECTED": {
      return {
        ...state,
        fetching: false,
        error: action.payload
      }
    }
    case "FETCH_POSTS_FULFILLED": {
      return {
        ...state,
        fetching: false,
        fetched: true,
        posts: action.payload
      }
    }
  }

  return state
}

这就是我提取类别信息的方式:

export const fetchCategory = (id) => {
  return {
    type: "FETCH_CATEGORY",
    payload: axios.get(`${REST_URL}/wp/v2/categories/${id}`)
  }
}

有没有办法将我的fetchPosts()操作与fetchCategory()操作结合起来,因此它会填充从post.categories返回的fetchPosts() fetchCategory()更详细run()信息?

1 个答案:

答案 0 :(得分:1)

如果您指的是ajax调用链接,您可以使用此示例来了解thunk如何为您服务:

function loadSomeThings() {
    return dispatch => {
        fetchFirstThingAsync.then(data => { // first API call
            dispatch({ type: 'FIRST_THING_SUCESS', data }); // you can dispatch this action if you want to let reducers take care of the first API call
            return fetchSecondThingAsync(data), // another API call with the data received from the first call that returns a promise
        })
        .then(data => {
             dispatch({ type: 'SECOND_THING_SUCESS', data }); // the reducers will handle this one as its the object they are waiting for
        });
    };
}

基本上,当我们调用loadSomeThings时,我们将新的action作为函数(fetchFirstThingAsync)作为我们的第一个ajax调用发送,redux-thunk将在任何reducer执行之前捕获它函数不是reducers可以处理的普通对象,thunk将以function作为参数调用此dispatchergetState以及更多args),我们用.then等待它然后我们可以发送一个reducers可以处理的普通对象+返回另一个承诺(fetchSecondThingAsync),这是你的第二个ajax调用,我们等待.then 1}}并再次调度reducers可以处理的普通对象。