如何在React应用中存储旧数据,该应用每5秒更新一次数据?

huangapple go评论71阅读模式
英文:

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个)。这里有一个使用随机数字作为值的完整示例:

在TS Playground中查看代码

<!-- 开始片段: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:

Code in TS Playground

<!-- 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 -->

&lt;div id=&quot;root&quot;&gt;&lt;/div&gt;&lt;script src=&quot;https://cdn.jsdelivr.net/npm/react@18.2.0/umd/react.development.js&quot;&gt;&lt;/script&gt;&lt;script src=&quot;https://cdn.jsdelivr.net/npm/react-dom@18.2.0/umd/react-dom.development.js&quot;&gt;&lt;/script&gt;&lt;script src=&quot;https://cdn.jsdelivr.net/npm/@babel/standalone@7.22.5/babel.min.js&quot;&gt;&lt;/script&gt;&lt;script&gt;Babel.registerPreset(&quot;tsx&quot;, {presets: [[Babel.availablePresets[&quot;typescript&quot;], {allExtensions: true, isTSX: true}]]});&lt;/script&gt;
&lt;script type=&quot;text/babel&quot; data-type=&quot;module&quot; data-presets=&quot;tsx,react&quot;&gt;
import type { ReactElement } from &quot;react&quot;;
// This Stack Overflow snippet demo uses UMD modules
const {
StrictMode,
useEffect,
useState,
} = React;
/** Simulated API call */
function getRandomDigitApi(): Promise&lt;number&gt; {
return Promise.resolve(Math.floor(Math.random() * 10));
}
function App(): ReactElement {
const [history, setHistory] = useState&lt;readonly number[]&gt;([]);
const [latest] = history;
useEffect(() =&gt; {
const intervalId = setInterval(
async () =&gt; {
const digit = await getRandomDigitApi();
// Only keep the last 5 values
setHistory(hist =&gt; [digit, ...hist.slice(0, 4)]);
},
1e3, // Repeat every 1 second
);
return () =&gt; clearInterval(intervalId);
}, []);
if (typeof latest !== &quot;number&quot;) return &lt;div&gt;No data yet&lt;/div&gt;;
return (
&lt;div&gt;
&lt;div&gt;Latest value: {latest}&lt;/div&gt;
&lt;div&gt;Recent values:&lt;/div&gt;
&lt;ul&gt;
{
history.slice(1).map((n, index) =&gt; (
&lt;li key={`${index}-${n}`}&gt;{n}&lt;/li&gt;
))
}
&lt;/ul&gt;
&lt;/div&gt;
);
}
ReactDOM.createRoot(document.getElementById(&quot;root&quot;)!).render(
&lt;StrictMode&gt;
&lt;App /&gt;
&lt;/StrictMode&gt;
);
&lt;/script&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月9日 04:43:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76435558.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定