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

bie*_*ier 25 reactjs react-redux

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

小智 49

的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()]));
}
Run Code Online (Sandbox Code Playgroud)

上面使用的行动:

(注意:您可以定义许多操作,例如fetchPostRequest可用于显示加载指示符.或者您可以在不同的HTTP状态代码的情况下调度不同的操作.)

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

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

function fetchPostsError() {
  return {
    type: "FETCH_ERROR"
  }
}
Run Code Online (Sandbox Code Playgroud)

在您的减速机中,您可以将帖子加载到州;

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

连接后,您可以访问组件中的状态和操作;

connect(mapStateToProps, {fetchPostsWithRedux})(App);
Run Code Online (Sandbox Code Playgroud)


Fra*_*nco 10

创建一个执行API请求的操作.您可以使用像axios或fetch这样的库来返回一个promise.

动作/ index.js:

import axios from 'axios';

export const FETCH_SOMETHING= 'FETCH_SOMETHING;
const ROOT_URL = 'http://api.youapi.com';

export function fetchWeather(city) {

    const url = `${ROOT_URL}&q=${aParamYouMayNeed}`;
    const request = axios.get(url);

    return {
        type: FETCH_SOMETHING,
        payload: request
    };
}
Run Code Online (Sandbox Code Playgroud)

然后在reducer中,消除promise数据,如下所示:

减速器/ reducer_something.js:

import { FETCH_SOMETHING} from '../actions/index';

export default function(state = [], action) {
    switch (action.type) {
        case FETCH_SOMETHING:
        return [ action.payload.data, ...state ];
    }

    return state;
}
Run Code Online (Sandbox Code Playgroud)

代码借自Stephen Grider.这是他的回购:https://github.com/StephenGrider/ReduxCasts/tree/master/weather/src

  • @jhuang好问题.我忘了提及当我说"消耗承诺结果一旦解决如下"时,Stephen Grided提供的示例使用了一个名为redux-promise的库,它必须在入口点应用,如下所示:applyMiddleware(ReduxPromise)(createStore) ); 该库处理承诺,使您的代码更清洁.https://www.npmjs.com/package/redux-promise (2认同)