在 React/Redux 架构中将 API 调用放在哪里? [英] Where to put API calls in React/Redux architecture?

查看:68
本文介绍了在 React/Redux 架构中将 API 调用放在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从 API 检索一些数据并将其传递到我的应用程序中.然而,作为 React/Redux 的新手,我想知道从哪里进行这些调用以及如何将其传递到我的应用程序中?我有标准的文件夹结构(组件、reducer、容器等),但我不确定现在将 API 调用放在哪里.

I am trying to retrieve some data from an API and pass it into my application. Being new to React/Redux however, I am wondering where to make these calls from and how to pass it into my application? I have the standard folder structure (components, reducers, containers, etc.) but I'm not sure where to place my API calls now.

推荐答案

最简单的入门方法是将其添加到您的操作中,使用称为 thunk 的函数以及 redux-thunk.您需要做的就是将 thunk 添加到您的商店:

The easiest way to get started with this is to just add it into your actions, using a function called a thunk along with redux-thunk. All you need to do is add thunk to your store:

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);

然后在您的操作中创建一个调用 api 的函数:

Then create a function in your actions that calls the api:

export const getData() {
  (dispatch) => {
    return fetch('/api/data')
      .then(response => response.json())
      .then(json => dispatch(resolvedGetData(json)))
  }
}

export const resolvedGetData(data) {
  return {
    type: 'RESOLVED_GET_DATA',
    data
  }
}

这篇关于在 React/Redux 架构中将 API 调用放在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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