我在react js中的以下组件中收到此警告React Hook React.useEffect缺少依赖项:"loadData"。请将其包括在内或删除依赖项数组。不知道出了什么问题
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>
);
};
有两种可能的解决方案可以实现,一种是在useEffect
中移动loadData
函数,但在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]);
另一种是将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]);