小编典典

如何通过Redux中的api获取数据?

reactjs

我是reactjs / redux的初学者,找不到如何使用api调用在redux应用程序中检索数据的简单示例。我猜您可以使用jquery
ajax调用,但是那里可能还有更好的选择?


阅读 747

收藏
2020-07-22

共1个答案

小编典典

JSfiddle;
http://jsfiddle.net/cdagli/b2uq8704/6/

它使用redux,redux-thunk和fetch。

提取方法;

function fetchPostsWithRedux() {
    return (dispatch) => {
    dispatch(fetchPostsRequest());
    return fetchPosts().then(([response, json]) =>{
        if(response.status === 200){
        dispatch(fetchPostsSuccess(json))
      }
      else{
        dispatch(fetchPostsError())
      }
    })
  }
}

function fetchPosts() {
  const URL = "https://jsonplaceholder.typicode.com/posts";
  return fetch(URL, { method: 'GET'})
     .then( response => Promise.all([response, response.json()]));
}

上面使用的动作:

(注意:您可以定义许多动作,例如fetchPostRequest可用于显示加载指示符。或者,如果HTTP状态码不同,则可以分派不同的动作。)

function fetchPostsRequest(){
  return {
    type: "FETCH_REQUEST"
  }
}

function fetchPostsSuccess(payload) {
  return {
    type: "FETCH_SUCCESS",
    payload
  }
}

function fetchPostsError() {
  return {
    type: "FETCH_ERROR"
  }
}

在您的reducer中,您可以加载帖子以声明状态;

const reducer = (state = {}, action) => {
  switch (action.type) {
    case "FETCH_REQUEST":
      return state;
    case "FETCH_SUCCESS": 
      return {...state, posts: action.payload};
    default:
      return state;
  }
}

连接它们之后,您可以访问组件中的状态和动作;

connect(mapStateToProps, {fetchPostsWithRedux})(App);
2020-07-22