[英]Eslint React Hooks Error: eslint-plugin-react-hooks exhaustive deps warning for a function dependency in useEffect
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Actions from '../actions'; export const UserComponent = ({ foo, baz, bar, user, fetchUser }) => { useEffect(() => { console.log('##### I WAS CALLED I WAS CALLED'); fetchUser(); }, []); return ( <div> <p>{user.name}</p> <p>{foo} {baz} {bar}</p> </div> ); }; UserComponent.propTypes = { fetchUser: PropTypes.func.isRequired, user: PropTypes.shape({}), }; const mapActionsToProps = { fetchUser: Actions.fetchUser, }; const mapStateToProps = ({ data }) => ({ user: data.user, }); export default connect(mapStateToProps, mapActionsToProps)(UserComponent);
I get an error 'React Hook useEffect has a missing dependency` 我收到一个错误消息:“ React Hook useEffect缺少依赖项”
But If I put fetchUser
in the dependency array 但是如果我把
fetchUser
放在依赖数组中
useEffect(() => { console.log('##### I WAS CALLED I WAS CALLED'); fetchUser(); }, [fetchUser]);
It causes an infinite loop. 它导致无限循环。
I was using redux the wrong way in hook based components. 我在基于挂钩的组件中以错误的方式使用redux。 This guide helped me a lot to use
redux
in functional components using hooks. 该指南对我使用钩子在功能组件中使用
redux
有很大帮助。 https://react-redux.js.org/next/api/hooks https://react-redux.js.org/next/api/hooks
The problem is that the function fetchUser changes in each render. 问题在于,函数fetchUser在每个渲染中都会更改。 You can solve the problem using "useCallback".
您可以使用“ useCallback”解决问题。
Example: 例:
const initFetchMethod = useCallback(() => {
return dispatch(fetchUserAction())
}, [dispatch])
useEffect(() => {
initFetchMethod();
}, [initFetchMethod]);
References: 参考文献:
Disable the es-lint warning if fetchUser
action does not change in app lifecycle 如果
fetchUser
操作在应用程序生命周期中未更改,请禁用es-lint警告
Since fetchUser is an redux action and it is not going to change in your app lifecycle, i would say you can safely disable the rule for your case. 由于fetchUser是一个redux操作,它不会在您的应用程序生命周期中发生变化,所以我想说您可以放心地为您的案例禁用规则。
useEffect(() => {
console.log('##### I WAS CALLED I WAS CALLED');
fetchUser();
//eslint-disable-next-line import/no-extraneous-dependencies
}, []);
The error says, you need to put all resources(vars/functions) used by the effect callback inside the dependencies array. 该错误表明,您需要将效果回调使用的所有资源(变量/函数)放入依赖项数组中。
So, you need to put fetchUsers in the dependencies array. 因此,您需要将fetchUsers放入依赖关系数组中。 But, it will cause infinite loop.
但是,它将导致无限循环。 Because, fetchUsers instance is recreated everytime.
因为,每次都会重新创建fetchUsers实例。
You need to maintain a loading state for the api response. 您需要维护api响应的加载状态。 And, put a check in the callback like below:
然后,像下面这样在回调中进行检查:
useEffect(() => {
if(!user && !loading ) {
fetchUser();
}
}, [fetchUser, user]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.