javascript - 在 redux 中获取 api 的最佳方法是什么?
问题描述
当我们在应用程序中使用 redux 时,如何编写在反应应用程序中获取 api 资源的最佳方法。
我的动作文件是 actions.js
export const getData = (endpoint) => (dispatch, getState) => {
return fetch('http://localhost:8000/api/getdata').then(
response => response.json()).then(
json =>
dispatch({
type: actionType.SAVE_ORDER,
endpoint,
response:json
}))
}
这是获取api的最佳方法吗?
解决方案
上面的代码很好。但是您应该注意几点。
- 如果您想向用户显示加载器以进行 API 调用,那么您可能需要进行一些更改。
- 您可以使用 async/await 语法更简洁。
- 同样在 API 成功/失败时,您可能希望向用户显示一些通知。或者,您可以签入 componentWillReceiveProps 以显示通知,但缺点是它会检查每个道具更改。所以我大多避免它。
要解决此问题,您可以执行以下操作:
import { createAction } from 'redux-actions';
const getDataRequest = createAction('GET_DATA_REQUEST');
const getDataFailed = createAction('GET_DATA_FAILURE');
const getDataSuccess = createAction('GET_DATA_SUCCESS');
export function getData(endpoint) {
return async (dispatch) => {
dispatch(getDataRequest());
const { error, response } = await fetch('http://localhost:8000/api/getdata');
if (response) {
dispatch(getDataSuccess(response.data));
//This is required only if you want to do something at component level
return true;
} else if (error) {
dispatch(getDataFailure(error));
//This is required only if you want to do something at component level
return false;
}
};
}
在您的组件中:
this.props.getData(endpoint)
.then((apiStatus) => {
if (!apiStatus) {
// Show some notification or toast here
}
});
您的减速器将如下所示:
case 'GET_DATA_REQUEST': {
return {...state, status: 'fetching'}
}
case 'GET_DATA_SUCCESS': {
return {...state, status: 'success'}
}
case 'GET_DATA_FAILURE': {
return {...state, status: 'failure'}
}
推荐阅读
- svg - 为什么 Safari 不显示我的 SVG 路径元素?
- json - 我可以从 IBM WATSON 中用 JSON 字符串编写的 HTML 代码中获取 HTML id
- mongodb - MGO 查询嵌套对象数组
- react-native - 什么反应本机组件以创建带有子项的列表
- php - 我怎样才能在laravel中放置计数器?
- python - 如何从数据库中获取与值列表匹配的记录?
- reactjs - antd 中的 getFieldDecorator 是什么,React 中的 getFieldDecorator 有什么用?
- jakarta-ee - 是否有 ManagedExecutorService 队列限制?
- mysql - 如何更新 MongoDB BI 连接器中的超时设置
- python-3.x - 如何使用python对二进制图像中的列和行像素求和