javascript - 在 redux 中获取 api 的最佳方式是什么?

标签 javascript node.js reactjs api redux

当我们在应用程序中使用 redux 时,如何编写在 React 应用程序中获取 api 资源的最佳方法。

我的 Action 文件是 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 的最佳方式吗?

最佳答案

上面的代码很好。但是有几点你应该注意。

  1. 如果您想向用户显示加载程序以进行 API 调用,那么您可能需要进行一些更改。
  2. 您可以使用 async/await,语法更加简洁。
  3. 此外,在 API 成功/失败时,您可能希望向用户显示一些通知。或者,您可以检查 componentWillReceiveProps 来显示通知,但缺点是它会检查每个 props 更改。所以我基本上避免它。

要解决这个问题,你可以这样做:

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
    }
});

你的 reducer 将是这样的:

case 'GET_DATA_REQUEST': {
    return {...state, status: 'fetching'}
}

case 'GET_DATA_SUCCESS': {
    return {...state, status: 'success'}
}

case 'GET_DATA_FAILURE': {
    return {...state, status: 'failure'}
}

关于javascript - 在 redux 中获取 api 的最佳方式是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52379391/

相关文章:

javascript - AngularJS - 多次 ng-click - 事件冒泡

node.js - web3.eth.sendSignedTransaction() 始终返回 "Returned error: nonce too low"

node.js - 导入应按字母顺序排序错误

javascript - 如何在 WordPress 中将 JavaScript 集成到网站的标题封面?

javascript - 使用标签/变量构建文本区域

javascript - 如何使用youtube api(v3)获取视频url

javascript - 如何将模式滚动显示在React.js中的顶部

javascript - reactjs axios 无法获取 api 数据

reactjs - 如何在 React 中引用本地镜像?

javascript - 将新的 Angular 模块导入到我的应用程序根目录