bim*_*mal 1 javascript api node.js reactjs 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
}))
}
Run Code Online (Sandbox Code Playgroud)
这是获取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;
}
};
}
Run Code Online (Sandbox Code Playgroud)
在您的组件中:
this.props.getData(endpoint)
.then((apiStatus) => {
if (!apiStatus) {
// Show some notification or toast here
}
});
Run Code Online (Sandbox Code Playgroud)
你的减速器将是这样的:
case 'GET_DATA_REQUEST': {
return {...state, status: 'fetching'}
}
case 'GET_DATA_SUCCESS': {
return {...state, status: 'success'}
}
case 'GET_DATA_FAILURE': {
return {...state, status: 'failure'}
}
Run Code Online (Sandbox Code Playgroud)