确定Redux中单个项目的本地缓存是否过期

Determine if local cache is stale for a single item in Redux

本文关键字:缓存 是否 过期 Redux 单个 项目 确定      更新时间:2023-09-26

在Redux异步示例中,有一个名为shouldFetch的函数,它接受(state, subreddit)并返回是否应该获取给定subreddit中的项。

你怎么能可靠地做同样的事情,但只有一个项目?表示取shouldFetch(state, subreddit, id)返回Boolean的函数。

真正的问题是你如何保持metadata时,每个项目被获取?我们存储的是lastUpdated中获取列表的时间,而不是每个条目最后一次更新的时间。

你需要:1. 确定项目是否甚至在缓存(存储)中2. 确定当前是否正在获取此当前项(通过列表获取或通过单独获取)3.判断物品是否过期

除了为lastUpdated/is抓取建立客户端数据库之外,还有什么好的方法来实现这个吗?

你怎么能可靠地做同样的事情,但只有一个项目?意思是一个函数接受shouldFetch(state, subreddit, id)并返回布尔值。

作为链接中的shouldFetchPosts函数,您必须创建自己的函数来检查某些元数据是否有某些内容。这部分不是关于redux,而是关于元数据,如何在redux存储上塑造数据,或者您需要的元数据是否在服务器响应中可用。

因此,您必须创建一个函数,该函数接受一些数据并检查您在函数体中编写的逻辑的给定数据。

真正的问题是如何保存每个条目被获取时的元数据?我们存储的是lastUpdated中获取列表的时间,而不是每个条目最后一次更新的时间。

你的意思是你正在更新你的列表项目,而你没有为更新的列表发出服务器请求?如果不是,如果你只是发送一个请求来更新项目,也许也在你的redux状态下更新项目,这应该没问题。由于您的应用程序是一个SPA,如果您确定服务器上的数据已经更改,那么您可以轻松地更改redux状态,并且可能不会发出服务器请求。

你需要:1。确定item是否在缓存(存储)中2。确定当前项是否正在被获取(通过列表获取,或通过单独获取)判断物品是否过期

现在这是我的想法,你实际上应该检查是否有些数据是陈旧的或不是从你的组件,如果有些东西正在被提取,你不应该允许你的用户触发重新抓取,再次,如果一些数据不是陈旧的,你可以很容易地使一个函数在你的组件来决定是否一个用户触发的动作是必要的。

将所有这些逻辑移动到redux操作会使您的redux文件变得丑陋。但是,您可以塑造您的redux状态,随时改进它,并从状态中检查一些元数据以做出决策。

我实际上构建了一个redux-cached-api-middleware包,它有助于以缓存的方式与API进行交互。它保留了读取完成时间戳,这有助于确定缓存是否过期。例如:

import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import api from 'redux-cached-api-middleware';
import Items from './Items';
import Error from './Error';
class ExampleApp extends React.Component {
  componentDidMount() {
    this.props.fetchData();
  }
  render() {
    const { result } = this.props;
    if (!result) return null;
    if (result.fetching) return <div>Loading...</div>;
    if (result.error) return <Error data={result.errorPayload} />;
    if (result.successPayload) return <Items data={result.successPayload} />;
    return <div>No items</div>;
  }
}
ExampleApp.propTypes = {
  fetchData: PropTypes.func.isRequired,
  result: PropTypes.shape({}),
};
const CACHE_KEY = 'GET/items';
const enhance = connect(
  state => ({
    result: api.selectors.getResult(state, CACHE_KEY),
  }),
  dispatch => ({
    fetchData() {
      return dispatch(
        api.actions.invoke({
          method: 'GET',
          headers: { Accept: 'application/json' },
          endpoint: 'https://my-api.com/items/',
          cache: {
            key: CACHE_KEY,
            strategy: api.cache
              .get(api.constants.CACHE_TYPES.TTL_SUCCESS)
              .buildStrategy({ ttl: 10 * 60 * 1000 }), // 10 minutes
          },
        })
      );
    },
  })
);
export default enhance(ExampleApp);

该组件使用一种缓存策略,来确定在调用this.props.fetchData();函数时是否应该重新获取资源。

如果你有一个更复杂的方法来确定缓存的有效性,你也可以提供一个自定义的shouldFetch函数:

const enhance = connect(
  state => ({
    result: api.selectors.getResult(state, CACHE_KEY),
  }),
  dispatch => ({
    fetchData() {
      return dispatch(
        api.actions.invoke({
          method: 'GET',
          headers: { Accept: 'application/json' },
          endpoint: 'https://my-api.com/items/',
          cache: {
            key: CACHE_KEY,
            strategy: api.cache   
            shouldFetch({ state }) { // CachedApiState object
              // Define your logic when the resource should be re-fetched
              return true;
            }
          },
        })
      );
    },
  })
);

* CachedApiState对象由以下字段组成:

{
  fetching: boolean, // is fetching in progress
  fetched: boolean, // was any fetch completed
  error: boolean, // was last response an error
  timestamp: ?number, // last response timestamp
  successPayload: ?any, // last success response payload
  errorPayload: ?any, // last error response payload
}