我正在尝试从 API 检索一些数据并将其传递到我的应用程序中。然而,作为 React/Redux 的新手,我想知道从哪里进行这些调用以及如何将其传递到我的应用程序中?我有标准的文件夹结构(组件、减速器、容器等),但我不确定现在将 API 调用放在哪里。
开始使用此方法的最简单方法是将其添加到您的操作中,使用称为 thunk 的函数以及redux-thunk https://github.com/gaearon/redux-thunk#composition。您需要做的就是将 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
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)