如何使用 React useEffect 调用加载函数一次 [英] How to call loading function with React useEffect only once
问题描述
useEffect React 钩子将在每次更改时运行传入的函数.可以对此进行优化,使其仅在所需属性更改时调用.
如果我想从 componentDidMount
调用一个初始化函数而不在更改时再次调用它怎么办?假设我想加载一个实体,但加载函数不需要来自组件的任何数据.我们如何使用 useEffect
钩子来做到这一点?
class MyComponent 扩展 React.PureComponent {componentDidMount() {loadDataOnlyOnce();}使成为() { ... }}
使用钩子,这看起来像这样:
function MyComponent() {useEffect(() => {loadDataOnlyOnce();//这将在每次更改时触发 :(}, [...???]);返回 (...);}
如果你只想在初始渲染后运行给 useEffect
的函数,你可以给它一个空数组作为第二个参数.
function MyComponent() {useEffect(() => {loadDataOnlyOnce();}, []);返回 {/* ... */} </div>;}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.
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 (...);
}
解决方案 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屋!
查看全文