首页 > web前端 > js教程 > 正文

如何在 React 中使用 useEffect 只调用一次函数?

Barbara Streisand
发布: 2024-10-17 21:58:29
原创
584 人浏览过

How to Invoke a Function Only Once in React Using useEffect?

How to Trigger a Function Only Once Using React's useEffect

React's useEffect hook serves as a replacement for class life-cycle methods. It allows developers to perform side effects in functional components. However, useEffect by default runs the provided function on every render.

Consider a scenario where you want to initialize data upon component mounting but prevent subsequent calls on state changes. For instance, loading an entity where the loading function doesn't depend on any component state.

Previously, in class components, this would be achieved using componentDidMount, which only triggers once. In functional components using useEffect, you can replicate this behavior as follows:

<code class="javascript">function MyComponent() {
    useEffect(() =&gt; {
        loadDataOnlyOnce(); // this will fire on every change :(
    }, [...???]);
    return (...);
}</code>
登录后复制

To restrict the function call to just the initial render, pass an empty array as the second argument to useEffect. This instructs React to execute the function only once, after the first render:

<code class="javascript">function MyComponent() {
  useEffect(() =&gt; {
    loadDataOnlyOnce();
  }, []);

  return &lt;div&gt; {/* ... */} &lt;/div&gt;;
}</code>
登录后复制

By following this approach, you can effectively trigger a loading function only once using React's useEffect hook, similar to how componentDidMount worked in class components.

以上是如何在 React 中使用 useEffect 只调用一次函数?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!