簡體   English   中英

用react redux做一個函數助手

[英]make a function helper with react redux

我是新來的人/ redux

當我在jquery中執行項目時,我將執行以下一些功能:

errorHandle (code) {
  if(code = 1){
    $('.popUpA').show()
  }
  ...
}

callAPI (){
  //Do AJAX call
  //If Error , call errorHandle()
}

在新項目中

我使用axios在api幫助器中調用API

export function getDataList(){
  //axios....
}

export function getData(){
  //axios....
}

然后使用Store觸發show / hide popUp,我將在組件中使用dispatch(showPopup())dispatch(showPopup(hide))

但我希望如果api函數具有error,將響應傳遞給errorHandler,然后調度showPopup。 我不知道如何將其添加到導出的功能。

有什么建議或例子嗎?

這是我對axios請求的抽象,我在與Redux一起使用的服務中使用了它:

 import axios from 'axios'; import { API } from '../../constants'; import { revokeAuthAction } from ; export const getAuth = () => { // Auth logic }; /** * Create an Axios Client with defaults */ const client = axios.create({ baseURL: API.BASEURL, headers: { Authorization: getAuth(), 'Access-Control-Max-Age': 1728000, // 'X-Authorization-JWT': }, }); /** * Request Wrapper with default success/error actions */ const request = (options) => { const onSuccess = (response) => options.raw ? response : response.data; // console.debug('Request Successful!', response); // If options.raw is true, return all response const onError = (error) => { // console.error('Request Failed:', error.config); if (error.response) { if (error.response.status === 401) { // console.error('Unauthorized'); store.dispatch(revokeAuthAction()); } else { // Request was made but server responded with something // other than 2xx // console.error('Status:', error.response.status); // console.error('Data:', error.response.data); // console.error('Headers:', error.response.headers); } } else { // Something else happened while setting up the request // triggered the error // console.error('Error Message:', error.message); } return Promise.reject(error.response || error.message); }; return client(options) .then(onSuccess) .catch(onError); // in realtà non catcho un bel niente perchè ritorno Promise.reject e quindi il giro ricomincia }; export default request; 

還有更多的庫來處理redux異步操作調用。 我使用redux-thunk另一個著名的庫是redux-saga。 使用redux thunk,您可以在redux中添加中間件,這樣您就可以創建返回操作的異步操作創建者,並且他們可以根據異步調用的結果調用其他操作創建者。

您可以通過以下方式添加中間件:

import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers/index';

// Note: this API requires redux@>=3.1.0
const store = createStore(
  rootReducer,
  applyMiddleware(thunk)
);

您的動作創建者將是這樣的:

export function requestDataList() {
  return function (dispatch: Function, getState: Function) {
    return getDataList().then(resp => {
      dispatch(dataListReceived(resp.data));
    }).catch(error => {
      dispatch(showPopup(title, error.message));
    });
  };
}

因此,如果您的getDataList重新運行axios承諾,則在成功時它將調用操作並返回結果。 出現錯誤時,可以調用錯誤對話框。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM