如何通过redux中的api获取数据? [英] How to fetch data through api in redux?

查看:156
本文介绍了如何通过redux中的api获取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 reactjs/redux 的初学者,找不到一个简单易用的示例,说明如何使用 api 调用在 redux 应用程序中检索数据.我想您可以使用 jquery ajax 调用,但可能有更好的选择吗?

I am a beginner with reactjs/redux, could not find a simple to use example of how to use an api call to retrieve data in a redux app. I guess you could use a jquery ajax call but there are probable better options out there?

推荐答案

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

它使用 redux、redux-thunk 和 fetch.

It uses redux, redux-thunk and 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 状态码的情况下调度不同的动作.)

(Note: You can define many actions e.g. fetchPostRequest can be used to display a loading indicator. Or you can dispatch different actions in case of different HTTP status codes.)

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

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

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

并且在您的减速器中,您可以加载帖子以进行状态;

And in your reducer you can load the posts to state;

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

您可以在连接后访问组件内的状态和动作;

You can access the state and actions within your component after connecting them with;

connect(mapStateToProps, {fetchPostsWithRedux})(App);

这篇关于如何通过redux中的api获取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆