简体   繁体   English

用react redux做一个函数助手

[英]make a function helper with react redux

I'm new to react / redux 我是新来的人/ redux

When I doing the project in jquery I will make some functions like this: 当我在jquery中执行项目时,我将执行以下一些功能:

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

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

In the new project, 在新项目中

I use the axios to call API in the api helper 我使用axios在api帮助器中调用API

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

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

And I use the Store to trigger the show/hide popUp , I will use dispatch(showPopup()) and dispatch(showPopup(hide)) in component 然后使用Store触发show / hide popUp,我将在组件中使用dispatch(showPopup())dispatch(showPopup(hide))

But I want that if api function have error , will pass the response in to the errorHandler , then dispatch the showPopup. 但我希望如果api函数具有error,将响应传递给errorHandler,然后调度showPopup。 I don't have idea how to add this into the exported function. 我不知道如何将其添加到导出的功能。

Any suggestion or example? 有什么建议或例子吗?

this is my abstraction of axios request, I use it in services that are used with Redux: 这是我对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; 

There are more library to handle redux async action calls. 还有更多的库来处理redux异步操作调用。 I use redux-thunk another well known library is redux-saga. 我使用redux-thunk另一个著名的库是redux-saga。 With redux thunk you will add a middleware to redux and this way you can create async action creators which return a function, and they can call other action creators depending of the result of the async call. 使用redux thunk,您可以在redux中添加中间件,这样您就可以创建返回操作的异步操作创建者,并且他们可以根据异步调用的结果调用其他操作创建者。

You add the middleware this way: 您可以通过以下方式添加中间件:

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

And your action creator will be something like this: 您的动作创建者将是这样的:

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

So if your getDataList retrun an axios promise, on success it will call an action wit the result. 因此,如果您的getDataList重新运行axios承诺,则在成功时它将调用操作并返回结果。 On error it can call the error dialog. 出现错误时,可以调用错误对话框。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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