javascript 使用Redux-Thunk缓存API响应

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 使用Redux-Thunk缓存API响应相关的知识,希望对你有一定的参考价值。

// Import the number of milliseconds before refetching
import { timeToStale } from './constants.js';

// First, define my allowed actions
const ACTIONS = {
  abort: "abort",
  error: "error",
  start: "start",
  update: "update"
}

// Log if a fetch is aborted by the async call running too aggressively.
export const abortFetch = () => ({
  type: ACTIONS.abort
});

/**
 * Log an error if the async call fails
 * @param {object} error - the error thrown.
 */
export const errorFetch = error => ({
  type: ACTIONS.error,
  error
});

// Start the fetch, toggle is `isFetching` value
export const startFetch = () => ({
  type: ACTIONS.start
});

/**
 * Resolve the fetch with the returned data
 * @param {object} payload - the data returned from the fetch 
 */
export const updateFetch = payload => ({
  type: ACTIONS.update,
  payload
});

// Run the async fetch if the data is stale, otherwise abort the fetch and log it
export const updateDemoContentAsync = () => {
  // Redux Thunk allows this, see its docs for more detail
  return (dispatch, getState) => {
    
    // Get the state of the store synchronously for the REDUCER IN QUESTION, e.g. myContent here
    const timeSinceLastFetch = getState().myContent.lastFetched;
    
    // perform the async call if the data is older than the allowed limit
    const isDataStale = Date.now() - timeSinceLastFetch > timeToStale;
    if (isDataStale) {
      dispatch(startFetch());

      // Run the async fetch
      myApi.fetchData()
        .then(content => {
          dispatch(updateFetch(content));
        })
        .catch(err => {
          dispatch(errorFetch(err));
        });
    } else {
      dispatch(abortFetch());
    }
  };
};

const initialState = {
  content: {},
  error: null,
  isFetching: false,
  lastFetched: 0
}

const myContentReducer = (state = initialState, action = {}) => {
  const { error, payload, type } = action;

  switch (type) {
     
    case ACTIONS.error: {
      return {
        ...state,
        error,
        isFetching: false
      };
    }

    case ACTIONS.startFetch: {
      return {
        ...state,
        isFetching: true
      };
    }

    case ACTIONS.update: {
      return {
        ...state,
        content: payload,
        error: null,
        isFetching: false,
        lastFetched: Date.now()
      };
    }

    default: {
      return state;
    }
  }
};

export default myContentReducer;
const numMinutesToStale = 60;
export const timeToStale = numMinutesToStale * 60 * 1000; 

以上是关于javascript 使用Redux-Thunk缓存API响应的主要内容,如果未能解决你的问题,请参考以下文章

javascript 惯性缓动实现

javascript Javascript中的简单缓动函数 - 请参阅https://github.com/gre/bezier-easing

如何使用“redux-thunk”调用 ajax?

使用redux-thunk完成异步connect的第二个参数的对象写法。

使用 axios 的 redux-thunk 的通用数据加载器

redux-thunk 的唯一好处是啥?