gpt4 book ai didi

reactjs - React Hook useEffect 缺少依赖项 Props

转载 作者:行者123 更新时间:2023-12-05 01:11:25 27 4
gpt4 key购买 nike

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

以下是我得到的错误:

React Hook useEffect has a missing dependency: 'props'. Either include it or remove the dependency array. However, 'props' willchange when any prop changes, so the preferred fix is to destructurethe 'props' object outside of the useEffect call and refer to thosespecific 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com