我正在尝试从 API 检索一些数据并将其传递到我的应用程序中。然而,作为 React/Redux 的新手,我想知道从哪里进行这些调用以及如何将其传递到我的应用程序中?我有标准的文件夹结构(组件、 reducer 、容器等),但我不确定现在将 API 调用放在哪里。
最佳答案
开始使用此方法的最简单方法是将其添加到您的操作中,使用名为 thunk 的函数以及 redux-thunk
。您需要做的就是将 thunk 添加到您的商店:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';
const store = createStore(
rootReducer,
applyMiddleware(thunk)
);
然后在您的操作中创建一个调用 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
}
}
关于reactjs - React/Redux 架构中 API 调用应该放在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40250036/