如何缓存API响应并在react & redux中稍后使用?

vyswwuz2  于 12个月前  发布在  React
关注(0)|答案(5)|浏览(117)

在我基于React的应用程序中,有一个rest API调用,它可以一次性获取整个页面所需的所有数据。响应中的数据也可以用于下拉列表中。但我不知道如何才能做到这一点。每当选择下拉值时,我当前正在发出新请求。请建议我如何有效地实现它,而不需要多次不必要的休息调用。

jhdbpxl9

jhdbpxl91#

您可以在HDD或RAM中缓存。

  • HDD =例如localStorage
  • RAM =应用程序状态,例如Redux商店。
    对于localStorage,您可以使用我的小插件:https://www.npmjs.com/package/localstorage-ttl
    在应用程序状态(RAM)- fire action来获取数据,使用redux-thunk,redux-saga或类似的方法进行调用,并使用reducer将数据保存在商店中。从存储中删除数据。

https://github.com/gaearon/redux-thunkhttps://github.com/redux-saga/redux-saga

8mmmxcuj

8mmmxcuj2#

您可以选择redux-cached-api-middleware(免责声明:我是这个库的作者),这是专门为这种情况而建的。
这里有一个例子,可能适合你的情况:

import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import api from 'redux-cached-api-middleware';
import Dropdown from './Dropdown';
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 <Dropdown items={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.SIMPLE_SUCCESS)
              .buildStrategy(),
          },
        })
      );
    },
  })
);

export default enhance(ExampleApp);

它只从API获取一次,无论何时调用fetchData,它都将从该高速缓存返回数据,即使调用来自另一个组件。
此库的设置如下:

import { createStore, combineReducers, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { apiMiddleware } from 'redux-api-middleware';
import api from 'redux-cached-api-middleware';
import reducers from './reducers';

const store = createStore(
  combineReducers({
    ...reducers,
    [api.constants.NAME]: api.reducer,
  }),
  applyMiddleware(thunk, apiMiddleware)
);

使用这种方法,在用户重新加载页面后,所有的redux状态都会丢失,如果你想保存该状态,你可以选择一个redux-persist库将状态同步到localStorage,并且可能会使用不同的redux-cached-api-middleware缓存策略。

jv4diomz

jv4diomz3#

你可以使用这个NPM库,它有一个内置的缓存。这就是你要找的东西。
https://www.npmjs.com/package/reqmate
检查示例

const response = await reqmate
  .get('https://jsonplaceholder.typicode.com/todos/1')
  .setCaching(3000) 
  .send();

在设置了该高速缓存之后,它会自动检测你是否发送了相同的缓存请求,并且它会给予你该高速缓存中的所有内容,直到它过期。

2mbi3lxu

2mbi3lxu4#

正如我猜测的那样,你正在使用redux进行状态管理。你想缓存API调用有效的控制状态的变化,以避免重新渲染组件,不必要的API调用和友好的移动的用户(避免fetchig相同的数据(未更改)多次)。如果是这样->那么你可以使用现成的解决方案。

**redux-cache.**请访问下面的链接获取更多信息,并简要调查缓存机制->何时需要缓存数据以及何时需要驱逐缓存。

https://github.com/JumboInteractiveLimited/redux-cache
如何在Redux中实现缓存?

bnlyeluc

bnlyeluc5#

如果您可以控制API,则可以调整它,以便缓存响应。https://web.dev/http-cache/

相关问题