【问题标题】:how to render react functional component after interval如何在间隔后渲染反应功能组件
【发布时间】:2022-01-06 13:10:16
【问题描述】:
  useEffect(() => {
    const url = `https://......com/..../${id}`;
    fetch(url)
      .then((res) => res.json())
      .then((data) => {
        console.log(serviceDetail);
        setServiceDetail(data);
      });

注意:我希望它每隔 5 秒渲染一次。(或多或少)

【问题讨论】:

  • 你尝试用什么代码来解决这个问题?
  • 不解决问题。我希望它在 5 秒等特定时间后渲染。
  • 你想每五秒调用一次 api 吗?
  • 是的,类似的。

标签: reactjs react-hooks functional-programming render intervals


【解决方案1】:

试试这个有帮助的代码

function App() {
  const [serviceDetail, setServiceDetail] = useState(0);

  const handleApiCall = () => {
    const url = 'https://......com/..../${id}';
    fetch(url).then((res) => res.json()).then((data) => {
      console.log(serviceDetail); setServiceDetail(data);
    });
  }
  useEffect(() => {
    handleApiCall(); //for call api init time 
   
   const interval = setInterval(() => {
      handleApiCall(); // call api after 5 seconds
    }, 5000);

    return () => clearInterval(interval); // clear interval after component unmounts.
  });

  return (
    <div>

    </div>
  );
}
export default App;

【讨论】:

  • 组件卸载时需要clearInterval。您可以通过从useEffect 返回一个thunk () =&gt; { ... } 来做到这一点。请参阅文档中的Effects with cleanup
【解决方案2】:

(当前)接受的答案遗漏了一个重要细节。当组件卸载时,间隔将继续运行。要阻止它,您需要clearInterval。另一个错误是 useEffect 在没有依赖关系的情况下被调用。这里我们使用useCallback 来生成一个仅在id 更新时才会更新的函数。回调和id 都作为依赖项传递给useEffect -

const [data, setData] = useState(...)

const update = useCallback(id =>
  fetch(`http://.../${id}/`)
    .then(r => r.json())
    .then(setData),
  [id]
)

useEffect(() => {
  const t = setInterval(_ => update(id), 5000)
  return () => clearInterval(t)
}, [update, id])

related Q&A 中,我们引入了一个自定义的useInterval 钩子,使组件可以轻松地处理基于间隔的状态。有关功能齐全的代码演示,请参阅帖子。

【讨论】:

    猜你喜欢
    • 2022-07-21
    • 1970-01-01
    • 2021-08-28
    • 2020-12-07
    • 2020-11-15
    • 2021-10-23
    • 2020-03-18
    • 1970-01-01
    • 2017-09-19
    相关资源
    最近更新 更多