使用效果.找到定义它的父组件,并将该定义包装在useCallback中



所以这是我在配置文件操作中的代码

import axios from 'axios';
import { GET_PROFILE, PROFILE_ERROR } from './types';
// Get current users profile
export const getCurrentProfile = () => async (dispatch) => {
try {
const res = await axios.get('/api/profile/me');
dispatch({
type: GET_PROFILE,
payload: res.data,
});
dispatch(getCurrentProfile());
} catch (err) {
dispatch({
type: PROFILE_ERROR,
payload: {
msg: err.response.statusText,
status: err.response.status,
},
});
}
};

这是我的仪表板

import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { getCurrentProfile } from '../../actions/profile';
const Dashboard = ({ getCurrentProfile, auth, profile }) => {
useEffect(() => {
getCurrentProfile();
}, []);
return <div>Dashboard</div>;
};
Dashboard.propTypes = {
getCurrentProfile: PropTypes.func.isRequired,
auth: PropTypes.object.isRequired,
profile: PropTypes.object.isRequired,
};
const mapStateToProps = (state) => ({
auth: state.auth,
profile: state.profile,
});
export default connect(mapStateToProps, { getCurrentProfile })(Dashboard);

我得到这个错误"React Hook useEffect有一个缺少的依赖项:'getCurrentProfile'。要么包含它,要么删除依赖项数组。如果'getCurrentProfile'更改太频繁,请找到定义它的父组件并将该定义包装在useCallback中">

正如警告所说,您可以将getCurrentProfile作为依赖项包含在useEffect中。

此外,由于getCurrentProfile函数作为dispatch function to props form connect传递,它的引用不会改变,因此您不必担心其引用的变化或using useCallback来记住它

useEffect(() => {
getCurrentProfile();
}, [getCurrentProfile]);

请注意,在 getCurrentProfile 函数中,您不得在没有条件的情况下调度自身

export const getCurrentProfile = () => async (dispatch) => {
try {
const res = await axios.get('/api/profile/me');
dispatch({
type: GET_PROFILE,
payload: res.data,
});
} catch (err) {
dispatch({
type: PROFILE_ERROR,
payload: {
msg: err.response.statusText,
status: err.response.status,
},
});
}
};

我想这是带有 react-hooks 插件的 eslint 的错误。该错误意味着当您使用接受数组作为依赖项的钩子时,插件建议在钩子函数中添加任何变量 function...,这些变量有机会更改每个渲染以包含在依赖项数组中。那么如何解决呢?

  • 您可以将getCurrentProfile包含在依赖项数组中,但如果定义组件或自定义挂钩,请确保使用useCallback来包装getCurrentProfile
  • 如果您愿意,您可以通过以下方式禁用 eslint 的效果
useEffect(() => {
getCurrentProfile();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

最新更新