如何缓存 API 响应并稍后在 react & 中使用它还原? [英] How to cache API response and use it later in react & redux?
问题描述
在我基于 React 的应用程序中,有一个 rest API 调用,它一次性获取整个页面所需的所有数据.响应中的数据也可用于下拉列表.但我不确定如何实现这一点.I am currently making a new request whenever the drop-down value is selected.请建议我如何有效地实现它,而不会发出多次不需要的休息调用.
In my React based application, there is a rest API call which fetches all the data in one shot which is needed for the whole page. The response has data which can be used in a population of dropdowns as well. But I am not sure how this can be achieved. I am currently making a new request whenever the drop-down value is selected. Please do suggest me how to do implement it efficiently without making multiple unwanted rest calls.
推荐答案
您可以缓存在 HDD 或 RAM 中.
you can cache in HDD or RAM.
- HDD = 例如本地存储
- RAM = 应用程序状态,例如还原商店.
对于 localStorage 你可以使用我的小插件:https://www.npmjs.com/package/localstorage-ttl
For localStorage you can use my little plugin for this: https://www.npmjs.com/package/localstorage-ttl
在应用状态 (RAM) - 触发操作以获取数据,使用 redux-thunk、redux-saga 或类似方法进行调用并使用 reducer 将数据保存在商店中.从存储中检索数据.
In app state (RAM) - fire action to fetch data, use redux-thunk, redux-saga or similar to make a call and with reducer save data in the store. Retrieve data from store.
https://github.com/gaearon/redux-thunkhttps://github.com/redux-saga/redux-saga
这篇关于如何缓存 API 响应并稍后在 react & 中使用它还原?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!