从 React.useEffect 中的依赖项列表中省略函数道具? [英] Omit function props from the dependencies list in React.useEffect?

查看:48
本文介绍了从 React.useEffect 中的依赖项列表中省略函数道具?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码块:

function foo({ bar, func }) {useEffect(() => {功能(酒吧)}, [func, bar])....}

这是一种在 React.useEffect 的依赖项列表中包含 func 的反模式吗?我的印象是 func 的函数定义几乎从不改变.如果我错了,请纠正我.

解决方案

这取决于 func 的值,显然是在父组件中初始化的

但是假设 func 被设置为一个永远不会改变的常量函数(大多数情况下是这样)那么不需要在这里添加它,你可以离开 bar并从 useEffect

的第二个参数中删除 func

但是这里的错误做法是,在您的代码中,如果 func 设置为一个增加 bar 的函数,例如

const func = (bar) =>酒吧 + 1;

这最终会无限地触发useEffect,因为每次bar改变useEffect都会被触发并增加bar 以此类推.

如果您想知道 func 是否可以更改

我会给你一个示例父组件,func 会在按钮点击时改变.

import React, {useState} from "react";const ParentComponent = () =>{const 增量 = bar =>酒吧+1;const 递减 = bar =>酒吧-1;const [func, setFunc] = useState(increment);返回 

//当这个按钮被点击时,`func`的值会发生变化<button onClick={() =>setFunc(decrement)}/>//这是你的组件<foo func={func}/>

}

I have the following block of code:

function foo({ bar, func }) {
  useEffect(() => {
    func(bar)
  }, [func, bar])

  ....
}

Is this an anti pattern to include func within the dependencies list for React.useEffect? I'm under the impression that the function definition for func almost never changes. Please correct me if I'm wrong.

解决方案

This depends on the value of func that is obviously initialized in the parent component

But assuming func is set to a constant function that will never change (which is mostly the case) then no need to add it here, you could just leave bar and remove func from the second argument of useEffect

However the bad practice here, in your code if func is set to a function that increments bar for example

const func = (bar) => bar + 1;

This will end up triggering the useEffect infinitely, because everytime bar changes the useEffect will be triggered and increment bar again and so on.

In case you're wondering if func can ever be changed

I'll give you an example parent component that func will change on a button click.

import React, {useState} from "react";

const ParentComponent = () => {
    const increment = bar => bar+1;
    const decrement = bar => bar-1;

    const [func, setFunc] = useState(increment);

    return <div>
         //When this button is clicked, `func` value will be changed
         <button onClick={() => setFunc(decrement)}/>

         // This is your component
         <foo func={func}/>
    </div>
}

这篇关于从 React.useEffect 中的依赖项列表中省略函数道具?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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