[英]React Hook React.useEffect has a missing dependency: 'loadData'. Either include it or remove the dependency array
I am getting this warning in the following component in react js React Hook React.useEffect has a missing dependency: 'loadData'.我在 React js React Hook React.useEffect 的以下组件中收到此警告缺少依赖项:'loadData'。 Either include it or remove the dependency array.
包括它或删除依赖项数组。 can't figure out what is the issue
不知道是什么问题
const ManageCourses = (props) => {
const [data, setData] = React.useState([]);
const [loading, setLoading] = React.useState(false);
React.useEffect(() => {
loadData();
}, [props.instructor]);
const loadData = async () => {
setLoading(true);
await axios
.get(
"http://localhost:4000/api/instructorcourses/" +
props.instructor.InstructorID
)
.then((res) => {
setData(res.data);
setLoading(false);
});
};
return (
<div>
{console.log(props.instructor)}
<Row>
<Col span={19}></Col>
<Col span={4}>{/*<AddBadge loadData={loadData} />*/}</Col>
<Col span={1}></Col>
</Row>
<br />
<table className="table table-striped table-sm table-bordered small">
<thead>
<tr>
<th className="w-25">Badge Name</th>
<th className="w-75">Badge Detail</th>
<th>Action</th>
</tr>
</thead>
{!loading && (
<tbody>
{data.map((data, index) => ({
/*<SingleBadge data={data} key={index} loadData={loadData} />*/
}))}
</tbody>
)}
</table>
</div>
);
};
There are 2 possible solutions you can implement, one is move loadData
function in useEffect
but you won't be able to access this function outside useEffect
scope:您可以实施 2 种可能的解决方案,一种是在
useEffect
中移动loadData
function,但您将无法在 useEffect scope 之外访问此useEffect
:
React.useEffect(() => {
const loadData = async () => {
setLoading(true);
await axios
.get(
"http://localhost:4000/api/instructorcourses/" +
props.instructor.InstructorID
)
.then((res) => {
setData(res.data);
setLoading(false);
});
};
loadData();
}, [props.instructor]);
And the other is to wrap loadData
in useCallback
and add it in the dependencies of useEffect
:另一种是将
loadData
包装在useCallback
中,并将其添加到useEffect
的依赖项中:
const loadData = React.useCallback(async () => {
setLoading(true);
await axios
.get(
"http://localhost:4000/api/instructorcourses/" +
props.instructor.InstructorID
)
.then((res) => {
setData(res.data);
setLoading(false);
});
}, [props.instructor]);
React.useEffect(() => {
loadData();
}, [loadData]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.