reactjs - React Hook useEffect 缺少依赖项 Props

标签 reactjs react-redux react-hooks use-effect

在我的 react/redux 应用程序中,每次挂载组件时,我都会调用一个操作来从 redux 中的状态检索数据。我的方法不行

以下是我得到的错误:

React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array. However, 'props' will change when any prop changes, so the preferred fix is to destructure the 'props' object outside of the useEffect call and refer to those specific props inside useEffect react-hooks/exhaustive-deps

这是我的代码:

import { getInvoiceData } from "../../actions/tables"

const TableSection = (props) =>{

  useEffect(() => {
    props.getInvoiceData();
  }, []);


  const classes = useStyles();

(...)

TableSection.propTypes = {
  invoiceData: PropTypes.object
};

const mapStateToProps = (state) => ({
  invoiceData: state.tables.invoiceData,
});

export default connect(mapStateToProps, { getInvoiceData })(TableSection);

最佳答案

你传递给 useEffect() 的依赖数组是空的,但你正在使用 props。 getInvoiceData() 在里面,所以它缺少 props。像这样添加它:

  useEffect(() => {
    props.getInvoiceData();
  }, [props]);

最好解构你的 Prop :

const TableSection = ({invoiceData , getInvoiceData}) =>{

  useEffect(() => {
   getInvoiceData();
  }, [getInvoiceData]);
  
  // Use invoiceData here
  console.log(invoiceData);

依赖项用于让 useEffect() 知道它是否应该再次触发。由于您的 getInvoiceData 是函数,在这种情况下它只会触发一次,就像 componentDidMount() 一样。

关于reactjs - React Hook useEffect 缺少依赖项 Props,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63205014/

相关文章:

reactjs - useEffect 导致无限循环

javascript - 无法在react-native中加载图像

node.js - NPM Start 不启动本地服务器

javascript - 如何在 React 中等待一个 API 调用完成后再启动另一个 API 调用?

reactjs - 为什么react-redux connect不直接将Dumb Component作为参数?

javascript - socket.io 监听器在函数式 React 中触发太多次

reactjs - 为什么 useMemo 不内存值

reactjs - 如果组件的容器被移除,是否需要调用 `unmountComponentAtNode`?

javascript - Redux/React-Redux - 在 reducer 中使用 "state = XXX"

reactjs - 第二次调度时的相同操作不会调用传奇,而在第一次平局中它会正确执行