【问题标题】:How to cache API response and use it later in react & redux?如何缓存 API 响应并稍后在 react 和 redux 中使用?
【发布时间】:2018-04-01 05:39:18
【问题描述】:

在我的基于 React 的应用程序中,有一个 rest API 调用可以一次性获取整个页面所需的所有数据。响应中的数据也可用于下拉列表。但我不确定如何实现这一点。 I am currently making a new request whenever the drop-down value is selected.请建议我如何有效地实现它,而无需进行多次不需要的休息调用。

【问题讨论】:

  • 嗨,你实现了这个。如果是,请告诉我怎么做。?
  • 是的..我已经实现了这个..你必须创建一个状态变量来保存 json 响应或数据。然后使用 willreceiveprops 和 render,就可以使用 state 变量并实现了。

标签: reactjs redux react-redux


【解决方案1】:

您可以缓存在 HDD 或 RAM 中。

  • HDD = 例如本地存储
  • RAM = 应用程序状态,例如还原商店。

对于 localStorage,您可以使用我的小插件: https://www.npmjs.com/package/localstorage-ttl

在应用程序状态 (RAM) - 触发操作以获取数据,使用 redux-thunk、redux-saga 或类似方法进行调用并使用 reducer 将数据保存在存储中。从存储中检索数据。

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

【讨论】:

  • 我添加了 +1。而且我觉得有人(谁把-1)并没有理解redux和浏览器存储在内部的位置;)))
【解决方案2】:

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

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

https://github.com/JumboInteractiveLimited/redux-cache

How do I implement caching in Redux?

【讨论】:

    【解决方案3】:

    你可以选择一个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 并使用可能会使用caching strategyredux-cached-api-middleware 不同。

    【讨论】:

    【解决方案4】:

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

    【讨论】:

    • 不适用于授权端点
    猜你喜欢
    • 2019-06-13
    • 2014-12-11
    • 1970-01-01
    • 1970-01-01
    • 2018-07-05
    • 2023-02-21
    • 2021-04-08
    • 1970-01-01
    • 2017-09-03
    相关资源
    最近更新 更多