[英]What is the best way to fetch api in redux?
当我们在应用程序中使用redux时,如何编写最佳方法来获取React应用程序中的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的最佳方法吗?
上面的代码很好,但是您应该注意几点。
要解决此问题,您可以执行以下操作:
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'}
}
使用中间件是在React + Redux应用程序中进行API调用的最可持续的方式。 如果您使用的是Observables(也就是Rxjs),那么看起来就比redux-observable更合适。
否则,您可以使用redux-thunk或redux-saga 。
如果您要进行快速原型制作,则使用fetch从组件进行简单的API调用就足够了。 对于每个API调用,您将需要执行以下三个操作:
then
发车。 catch
块中调度。 例:
function mounted() {
store.dispatch(loadUsers());
getUsers()
.then((users) => store.dispatch(loadUsersSucc(users)))
.catch((err) => store.dispatch(loadUsersFail(err));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.