Home >Web Front-end >JS Tutorial >Detailed introduction to redux asynchronous operations (code example)

Detailed introduction to redux asynchronous operations (code example)

不言
不言forward
2018-11-20 14:38:342283browse

This article brings you a detailed introduction (code example) about redux asynchronous operations. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. Redux basics

redux

  • Through dispatch(action) - > Middleware -> reducer processes data -> Change store -> Use subscribe() to monitor store changes and update views to manage state

  • Store all states in one store The

  • reducer in the object is a pure function, and the asynchronous operation contains side effects due to the uncertainty of the result, so special handling is required

# #react-reduxContainer component, responsible for managing data and business logic, not responsible for UI presentation
UI component, provides UI presentation, stateless means not using this.state, all states are provided by this.props
Container components are generated by connect. Each time the store changes, connect will be called. connect receives two parameters: mapStateToProps, mapDispatchToProps
mapStateToProps, maps the state to the props of the UI component
mapDispatchToProps, maps the dispatch method to the UI The props of the component
Provider component uses the content API to pass the store from the top level to each layer of component for use by connect

2. Redux handles asynchronous middleware

redux-thunkredux-thunk middleware allows action to be a method
After receiving the action, the middleware will execute the action method and provide the result to the reducer
Action confusion leads to difficulty Maintenance

redux-sagasaga will listen to the action and perform Effects operations based on this action
Effects provides flexible APIs, including blocking and non-blocking calls, cancellation, waiting, race and other operations
Convenient to isolate and perform asynchronous operations, and easy to test

3. redux-request-async-middleware

Let’s start with the asynchronous action in the redux document , each interface call requires dispatching three synchronization actions, which are:

An action that notifies the reducer that the request has started. For this kind of action, the reducer may switch the isFetching tag in the state. This tells the UI to display the loading interface.
An action that notifies the reducer that the request is successful. For this kind of action, the reducer may merge the new data received into the state and reset isFetching. The UI will hide the loading interface and display the received data.
An action that notifies the reducer that the request failed. For this kind of action, the reducer may reset isFetching. In addition, some reducers will save these failure information and display it in the UI.
That is, an interface is initiated like this.

dispatch(fetchPostsRequest(subject));
fetch(url).then(res => {
  dispatch(fetchPostsSuccess(subject, res));
}).catch(e => {
  dispatch(fetchPostsFailure(subject, e));
})
Just encapsulates this operation into middleware. The special thing is:

  • Common to all asynchronous requests These three actions

  • Use subject to distinguish which request it is

  • Put all results in store.requests

Middleware source code

export const reduxRequest = store => next => action => {
  let result = next(action);
  let { type, subject, model } = action;
  let _next = action.next;
  if(type === FETCH_POSTS_REQUEST) {
    model().then(response => {
      _next && _next(response);
      store.dispatch(fetchPostsSuccess(subject, response));
    }).catch(error => {
      console.error(error);
      store.dispatch(fetchPostsFailure(subject, error));
    });
  }
  return result
};/
  • Same as redux-thunk, put the method into the action

  • Middle The software intercepts the FETCH_POSTS_REQUEST action and performs asynchronous processing

reducer source code

export const requests = (state = {}, action) => {
  switch (action.type) {
    case FETCH_POSTS_REQUEST:
      return assign({},
        state,
        {
          [action.subject]: {
            isFetching: true,
            state: 'loading',
            subject: action.subject,
            response: null,
            error: null,
          }
        }
      );
    case FETCH_POSTS_FAILURE:
      return assign({},
        state,
        {
          [action.subject]: {
            isFetching: false,
            state: 'error',
            subject: action.subject,
            response: state[action.subject].response,
            error: action.error,
          }
        }
      );
    case FETCH_POSTS_SUCCESS:
      return assign({},
        state,
        {
          [action.subject]: {
            isFetching: false,
            state: 'success',
            subject: action.subject,
            response: action.response,
          }
        }
      );
    case FETCH_POSTS_CLEAR:
      return assign({},
        state,
        {
          [action.subject]: {
            isFetching: false,
            state: 'cleared',
            subject: null,
            response: null,
            error: null,
          }
        }
      )
      return state;
  }
}
  • Put the result into the response corresponding to the subject, if it is wrong Put the error information into error

  • isFetching indicates the current request status

  • In addition, the current state state and subject information are also added

Encapsulate the request

const request = (subject, model, next) => {
  _dispatch(fetchPostsRequest(subject, model, next));
  return true;
};
  • Write a method to initiate the FETCH_POSTS_REQUEST action

  • In other words, write When making a request, you no longer need to worry about the action. Simply call the request method

to encapsulate the result.

const getResponse = state =>
  state
  && state.response !== null
  && state.response;
 
const getLoading = (states = []) =>
  states.reduce((pre, cur) =>
    pre || (cur && cur.isFetching)
    , false)
  || false;
  1. You can obtain the result and multiple The loading status under the request

  2. If there are more operations or formats, you can continue to encapsulate it, such as the list

4. Summary

  1. Using redux for state management, there is no need to write the complex logic of redux, minimizing the complexity of asynchronous operations

  2. Suitable for projects where the front end processes and stores data through interfaces

  3. The interface is processed by redux, while the view component is processed by the internal state, while only simple interfaces are exposed externally To operate, separate the business layer and the view layer

  4. Compared with react 16.3 new content API, the advantage of redux lies in the hot-insertion middleware and pure function reducer writing method

The above is the detailed content of Detailed introduction to redux asynchronous operations (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete