[英]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.在我的 react/redux 应用程序中,每次安装组件时,我都会调用一个操作来从 redux 中的 state 检索数据。 My way does not work
我的方法行不通
Below is the error I'm getting:以下是我得到的错误:
React Hook useEffect has a missing dependency: 'props'.
React Hook useEffect 缺少依赖项:'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
但是,当任何道具发生变化时,“道具”会发生变化,因此首选的解决方法是在 useEffect 调用之外解构“道具” object,并在 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:使用 react-redux 钩子,如
useSelector
和useDispatch
将最大限度地减少您的工作时间,这里您的代码带有 react-redux 钩子:
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()
您传递给
useEffect()
的依赖数组是空的,但您正在使用props. getInvoiceData()
props. getInvoiceData()
inside of it, so it's missing the props
. props. getInvoiceData()
里面,所以它缺少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.依赖项用于让
useEffect()
知道它是否应该再次触发。 Since your getInvoiceData
is function, in this case it will only fire once, just like componentDidMount()
.由于您的
getInvoiceData
是 function,在这种情况下它只会触发一次,就像componentDidMount()
一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.