英文:
how to storage old data in react app that updates data every 5 seconds
问题
我有一个React应用程序,显示从API获取的实时数据。数据每5秒钟变化一次,因此应用程序的渲染也相应变化。
我需要做的是将当前数据的一组分数保存起来,并在下一次更新时显示它们,以此类推,每次数据发生变化都要如此。
我使用的是函数组件,所以尝试将它们保存在状态中,但当数据发生变化时,它们当然不会被保存。
我该如何做呢?
英文:
I have a react app that shows realtime data that fetches from an API. the data changes every 5 seconds e the render of the app in consequence.
what I need to do is to save a set of scores from the current data and show them on the next update, and so on every time the data changes.
I have functional components so I tried to save them in a state but of course when the data changes it doesn't save them.
How can I do that?
答案1
得分: 0
您可以将API值的历史保存在一个数组状态值中。
将最新的值存储在数组的一端(例如,开头),并仅保留您需要的最近值的数量(例如,5个)。这里有一个使用随机数字作为值的完整示例:
<!-- 开始片段:js 隐藏:false 控制台:true 布尔值:false -->
<!-- 语言:lang-css -->
body { font-family: sans-serif; }
div { margin-top: 0.5rem; }
<!-- 语言:lang-html -->
<div id="root"></div><script src="https://cdn.jsdelivr.net/npm/react@18.2.0/umd/react.development.js"></script><script src="https://cdn.jsdelivr.net/npm/react-dom@18.2.0/umd/react-dom.development.js"></script><script src="https://cdn.jsdelivr.net/npm/@babel/standalone@7.22.5/babel.min.js"></script><script>Babel.registerPreset("tsx", {presets: [[Babel.availablePresets["typescript"], {allExtensions: true, isTSX: true}]]});</script>
<script type="text/babel" data-type="module" data-presets="tsx,react">
import type { ReactElement } from "react";
// This Stack Overflow snippet demo uses UMD modules
const {
StrictMode,
useEffect,
useState,
} = React;
/** Simulated API call */
function getRandomDigitApi(): Promise<number> {
return Promise.resolve(Math.floor(Math.random() * 10));
}
function App(): ReactElement {
const [history, setHistory] = useState<readonly number[]>([]);
const [latest] = history;
useEffect(() => {
const intervalId = setInterval(
async () => {
const digit = await getRandomDigitApi();
// Only keep the last 5 values
setHistory(hist => [digit, ...hist.slice(0, 4)]);
},
1e3, // Repeat every 1 second
);
return () => clearInterval(intervalId);
}, []);
if (typeof latest !== "number") return <div>No data yet</div>;
return (
<div>
<div>Latest value: {latest}</div>
<div>Recent values:</div>
<ul>
{
history.slice(1).map((n, index) => (
<li key={`${index}-${n}`}>{n}</li>
))
}
</ul>
</div>
);
}
ReactDOM.createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>
);
</script>
<!-- 结束片段 -->
英文:
You can save a history of your API values in an array state value.
Store the latest value at one end of the array (e.g. the beginning) and only keep the number of recent values that you need (e.g. 5). Here's a complete example using random numbers as values:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-css -->
body { font-family: sans-serif; }
div { margin-top: 0.5rem; }
<!-- language: lang-html -->
<div id="root"></div><script src="https://cdn.jsdelivr.net/npm/react@18.2.0/umd/react.development.js"></script><script src="https://cdn.jsdelivr.net/npm/react-dom@18.2.0/umd/react-dom.development.js"></script><script src="https://cdn.jsdelivr.net/npm/@babel/standalone@7.22.5/babel.min.js"></script><script>Babel.registerPreset("tsx", {presets: [[Babel.availablePresets["typescript"], {allExtensions: true, isTSX: true}]]});</script>
<script type="text/babel" data-type="module" data-presets="tsx,react">
import type { ReactElement } from "react";
// This Stack Overflow snippet demo uses UMD modules
const {
StrictMode,
useEffect,
useState,
} = React;
/** Simulated API call */
function getRandomDigitApi(): Promise<number> {
return Promise.resolve(Math.floor(Math.random() * 10));
}
function App(): ReactElement {
const [history, setHistory] = useState<readonly number[]>([]);
const [latest] = history;
useEffect(() => {
const intervalId = setInterval(
async () => {
const digit = await getRandomDigitApi();
// Only keep the last 5 values
setHistory(hist => [digit, ...hist.slice(0, 4)]);
},
1e3, // Repeat every 1 second
);
return () => clearInterval(intervalId);
}, []);
if (typeof latest !== "number") return <div>No data yet</div>;
return (
<div>
<div>Latest value: {latest}</div>
<div>Recent values:</div>
<ul>
{
history.slice(1).map((n, index) => (
<li key={`${index}-${n}`}>{n}</li>
))
}
</ul>
</div>
);
}
ReactDOM.createRoot(document.getElementById("root")!).render(
<StrictMode>
<App />
</StrictMode>
);
</script>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论