繁体   English   中英

在Redux中获取api的最佳方法是什么?

[英]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的最佳方法吗?

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

  1. 如果要向用户显示用于API调用的加载程序,则可能需要进行一些更改。
  2. 您可以使用async / await语法更加简洁。
  3. 同样在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'}
}

使用中间件是在React + Redux应用程序中进行API调用的最可持续的方式。 如果您使用的是Observables(也就是Rxjs),那么看起来就比redux-observable更合适。

否则,您可以使用redux-thunkredux-saga

如果您要进行快速原型制作,则使用fetch从组件进行简单的API调用就足够了。 对于每个API调用,您将需要执行以下三个操作:

  1. LOAD_USER-用于在API调用之前设置加载状态的操作。
  2. LOAD_USER_SUCC -API调用成功时。 then发车。
  3. LOAD_USER_FAIL-当API调用失败并且您可能想在Redux存储中设置值时。 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM