如何仅使用一次React useEffect调用加载函数 [英] How to call loading function with React useEffect only once

查看:1559
本文介绍了如何仅使用一次React useEffect调用加载函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

useEffect React挂钩将在每次更改时运行传入的函数.可以对其进行优化,使其仅在所需属性更改时调用它.

The useEffect React hook will run the passed in function on every change. This can be optimized to let it call only when the desired properties change.

如果我想从componentDidMount调用初始化函数而不在更改时再次调用该怎么办?假设我要加载一个实体,但是加载功能不需要组件中的任何数据.我们如何使用useEffect挂钩做到这一点?

What if I want to call an initialization function from componentDidMount and not call it again on changes? Let's say I want to load an entity, but the loading function doesn't need any data from the component. How can we make this using the useEffect hook?

class MyComponent extends React.PureComponent {
    componentDidMount() {
        loadDataOnlyOnce();
    }
    render() { ... }
}

使用钩子,可能看起来像这样:

With hooks this could look like this:

function MyComponent() {
    useEffect(() => {
        loadDataOnlyOnce(); // this will fire on every change :(
    }, [...???]);
    return (...);
}

推荐答案

如果只想在初始渲染后运行赋予useEffect的函数,则可以给它一个空数组作为第二个参数.

If you only want to run the function given to useEffect after the initial render, you can give it an empty array as second argument.

function MyComponent() {
  useEffect(() => {
    loadDataOnlyOnce();
  }, []);

  return <div> {/* ... */} </div>;
}

这篇关于如何仅使用一次React useEffect调用加载函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆