reactjs - 使用函数作为 useEffect 依赖项->“缺少依赖项'props'”
问题描述
我的意图是使用一个函数(由父组件接收,使用创建useCallback
)作为依赖项,useEffect
并且仅在函数更改时触发该效果。
考虑以下简单组件:
function MyComponent(props) {
const [myState, setMyState] = useState(0);
useEffect(() => {
setMyState(props.calculate(1));
}, [props.calculate])
return <h1>{myState}</h1>;
}
calculate
它在 props 中接收一个函数并myState
从中进行计算。但是我得到了 linting 错误:
React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array.
我不明白为什么props.calculate
作为依赖项还不够,我们需要props
. 我不想使用props
,因为这样效果会在每次渲染时重新触发,即使calculate
没有改变。(假设calculate
已使用useCallback
父级创建)。
以下版本不会出现任何 linting 错误:
function MyComponentVersion2(props) {
const { calculate } = props;
const [myState, setMyState] = useState(0);
useEffect(() => {
setMyState(calculate(1));
}, [calculate])
return <h1>{myState}</h1>;
}
我的问题是:
- 为什么 linter 不适合
MyComponent
? MyComponent
与 相比是否存在语义差异MyComponentVersion2
?
我在这个代码框里做了一个最小的例子
谢谢!
解决方案
这是因为调用props.calculate(1)
隐式地props
作为this
值传递给calculate
,所以从技术上讲,结果可能取决于整个props
对象(参见这个 React 问题)。对于解构calculate
调用,this
将是 undefined 或全局对象,因此不依赖props
.
(x) => {return x + 1;}
您可以通过替换function (x) {console.log(this); return x + 1;}
定义中的来查看两个组件之间的差异calculate
。
推荐阅读
- excel - 当我尝试访问 Access DB 时 Excel 崩溃
- image - 从顶点颜色创建图像纹理的算法
- c# - VSTS 未在 Release 中构建 Test.dll
- ubuntu - 如何知道 shell size 命令的单位?
- widget - 通过 Syncfusion Dashboard Designer 平台自定义小部件
- php - 419 auth 错误尝试使用 Laravel Echo、Vue 和 Pusher 设置事件
- ruby-on-rails - Rails has_many 表单可选地创建多条记录
- java - Android 7.1如何清除通知栏的所有通知?
- css - 简单的旋转悬停效果不起作用
- c# - “从范围''引用''类型的变量'',但未定义”