reactjs - 如何阻止 useEffect 一遍又一遍地重复
问题描述
import { useState, useEffect } from 'react';
import axios from 'axios';
export const GetData = (url) => {
const [data, setData] = useState([]);
useEffect(() => {
const getData = async () => {
try {
const response = await axios.get(url);
setData(response.data);
} catch (error) {
console.error(error);
}
};
getData();
return () => {};
}, [data]);
return {
data,
};
};
我将上面的组件用于多个多个组件。我的问题是请求不断重复。我想阻止它重复。它应该重复的唯一时间是“数据”发生变化时。我尝试使用 axios 的取消令牌,但没有奏效。我还尝试使用间隔来停止它(也许我做错了。我不知道)。下面的代码显示了我正在使用 GetData 组件的组件之一。希望这会有所帮助。
import React from 'react';
import { Card, Table, Button } from 'react-bootstrap';
import { DeleteData, GetData } from '../../../api';
import { useGlobalContext } from '../../../context';
const SectionTable = ({ url }) => {
const { setIsEdit, getId } = useGlobalContext();
const { data } = GetData(url);
return (
<>
<Card style={{ maxHeight: '500px', overflowY: 'scroll' }}>
<Card.Body>
<Table striped responsive hover>
<thead>
<th>Section Level</th>
<th>Section Name</th>
<th></th>
<th></th>
</thead>
<tbody>
{data.map((section) => {
return (
<tr key={section.id}>
<td>{section.section_level}</td>
<td>{section.section_name}</td>
<td>
<Button
variant='warning'
onClick={() => {
getId(section.id);
setIsEdit(true);
}}>
Edit
</Button>
</td>
<td>
<Button
variant='danger'
onClick={() => DeleteData(section.id)}>
Delete
</Button>
</td>
</tr>
);
})}
</tbody>
</Table>
</Card.Body>
</Card>
</>
);
};
export default SectionTable;
```**strong text**
解决方案
将数据列为依赖项意味着效果在每次由data
. 而是依赖于 url:
useEffect(() => {
const getData = async () => {
try {
const response = await axios.get(url);
setData(response.data);
} catch (error) {
console.error(error);
}
};
getData();
return () => {};
}, [url]);
推荐阅读
- c - 无限while循环中的信号
- c - 将 cmd 中的函数 system() 写入 C 中带有空格的某个路径时绕过空间问题
- python - 对列表的numpy数组进行排序
- java - 在 Intelli 中的 java 中使用 HtmlUnit 时出现 IncompatibleClassChangeError
- kotlin - 我们如何确定我们已经在交易区块中?
- multithreading - 如何在所有 GPU 线程上运行相同的 MATLAB 代码
- encryption - Flutter,RSA用两个私钥解密
- python - pytest-asyncio 猴子补丁 requests.post 不起作用
- flutter - 如何创建自定义半底导航布局
- c# - 当按下某个按钮时,会改变预制件的运动