简体   繁体   中英

React Hook useEffect has a missing dependency Props

In my react/redux app, i have an action that gets called to retrieve data from state in redux each time the component is mounted. My way does not work

Below is the error I'm getting:

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

Here is my code:

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);

using react-redux hooks like useSelector and useDispatch will minimize your work time, here your code with react-redux hooks:

import { getInvoiceData } from "../../actions/tables"
import {useSelector ,useDispatch} from "react-redux"

const TableSection = (props) =>{
const {invoiceData} = useSelector(state=>state.tables)
const dispatch = useDispatch()

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


  const classes = useStyles();

return (<div>
{// here do something with invoiceData}
{invoiceData && invoiceData.map(...)}
</div>)
}
TableSection.propTypes = {
  invoiceData: PropTypes.object
};

export default TableSection;

The dependency array you pass to useEffect() is empty, but you're using props. getInvoiceData() props. getInvoiceData() inside of it, so it's missing the props . Add it like this:

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

Better would be to deconstruct your props:

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

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

Dependencies are used to let useEffect() know if it should fire again or not. Since your getInvoiceData is function, in this case it will only fire once, just like componentDidMount() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM