React hooks 使用 eslint-plugin-react-hooks@next 附加不需要的值
React hooks appends unwanted value with eslint-plugin-react-hooks@next
我的组件中有一个 useEffect
挂钩,它调用 Redux 操作来获取一些数据。
useEffect(
() => {
props.getClientSummaryAction();
},[]
);
当我去保存文件时,linter 会执行此操作。
useEffect(
() => {
props.getClientSummaryAction();
}, [props]
);
这显然将我的组件发送到一个无限循环中,因为 getClientSummaryAction
获取一些更新道具的数据。
我已经使用了这样的解构,并且 linter 更新了数组。
const { getClientSummaryAction } = props;
useEffect(
() => {
getClientSummaryAction();
},
[getClientSummaryAction]
);
我觉得这很好,但它真的没有意义,因为 getClientSummaryAction
显然永远不会更新,它是一个函数。
我只想知道为什么 linter 会这样做以及这是否是最佳实践。
这不是不需要的。您知道依赖关系不会改变这一事实,但 React
可能知道这一点。规则很明确:
Either pass an array containing all dependencies or don't pass anything to the second argument and let React
keep track of changes.
把第二个参数传给useEffect
就是告诉React你负责hook的调用。因此,当您不传递包含在您的效果中的依赖项时,eslint
会将这视为可能的内存泄漏并会警告您。 DO NOT disable the rule 就像您已经在做的那样继续传递依赖关系。可能会觉得多余,但这是最好的。
我的组件中有一个 useEffect
挂钩,它调用 Redux 操作来获取一些数据。
useEffect(
() => {
props.getClientSummaryAction();
},[]
);
当我去保存文件时,linter 会执行此操作。
useEffect(
() => {
props.getClientSummaryAction();
}, [props]
);
这显然将我的组件发送到一个无限循环中,因为 getClientSummaryAction
获取一些更新道具的数据。
我已经使用了这样的解构,并且 linter 更新了数组。
const { getClientSummaryAction } = props;
useEffect(
() => {
getClientSummaryAction();
},
[getClientSummaryAction]
);
我觉得这很好,但它真的没有意义,因为 getClientSummaryAction
显然永远不会更新,它是一个函数。
我只想知道为什么 linter 会这样做以及这是否是最佳实践。
这不是不需要的。您知道依赖关系不会改变这一事实,但 React
可能知道这一点。规则很明确:
Either pass an array containing all dependencies or don't pass anything to the second argument and let
React
keep track of changes.
把第二个参数传给useEffect
就是告诉React你负责hook的调用。因此,当您不传递包含在您的效果中的依赖项时,eslint
会将这视为可能的内存泄漏并会警告您。 DO NOT disable the rule 就像您已经在做的那样继续传递依赖关系。可能会觉得多余,但这是最好的。