【问题标题】:How to fetch data through api in redux?如何在redux中通过api获取数据?
【发布时间】:2017-02-10 08:35:26
【问题描述】:

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

【问题讨论】:

标签: reactjs react-redux


【解决方案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"
  }
}

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

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);

【讨论】:

  • 奇怪,使用这个确切的代码我得到Uncaught (in promise) Error: Reducers may not dispatch actions.
  • 返回Promise.all([response, response.json()]) 有什么作用?为什么不返回response.json()
【解决方案2】:

创建一个操作,您可以在其中执行对 API 的请求。您可以使用 axios 或 fetch 之类的库来返回一个承诺。

actions/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
    };
}

然后在reducer中,使用promise的结果,一旦解决如下:

reducers/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;
}

从 Stephen Grider 借来的代码。这是他的仓库:https://github.com/StephenGrider/ReduxCasts/tree/master/weather/src

【讨论】:

  • 你有一个plunker之类的吗?
  • 否,但您可以在 myresponse 中克隆样本(刚刚编辑过),我已经测试过并且工作正常。
  • 为什么你不需要在reducer 中使用.then() 来确保Promise 已经实现并且data 不是undefined
  • @jhuang 好问题。当我说“使用如下解决的承诺结果”时,我忘了提及 Stephen Grided 提供的示例使用了一个名为 redux-promise 的库,该库必须在入口点中应用,如下所示:applyMiddleware(ReduxPromise)(createStore );该库处理使您的代码更清洁的承诺。 npmjs.com/package/redux-promise
猜你喜欢
  • 2018-11-17
  • 2018-01-26
  • 1970-01-01
  • 2021-06-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-16
  • 1970-01-01
相关资源
最近更新 更多