javascript - axios调用给无限循环
问题描述
我需要获取一些数据并设置状态,但它给了我无限循环,我不知道如何解决这个问题。
我的 Routes.tsx 中的示例:
// get all posts
useEffect(() => {
Axios.get('/api/posts', config)
.then(res => setAllPosts(res.data))
.catch(err => console.log(err))
}, [config]);
如果我不依赖'config',它只会在刷新时显示结果,但它不会给我无限循环。
解决方案
尝试使用 useStata[] 和 useEffect[]
const [data, setData] = useState({ hits: [] });
useEffect(async () => {
const result = await axios.get('/api/posts', config)
.then(res => setAllPosts(res.data))
.catch(err => console.log(err))
setData(result);
}, []);
return (
<ul>
{data.posts.map(item => (
// stuff
))}
</ul>
);
推荐阅读
- ubuntu-18.04 - 在 Cloudstack 中添加主机的问题
- android - 我想从作为参数传递给对象构造函数的函数调用对象方法
- r - 管道行和的简单方法
- apache-spark - Hive Schema 删除非常慢。hive 可以在数据库上并行执行 drop table 语句吗?
- python - Django ImageField:直接使用磁盘中的文件
- php - 自动捆绑资产流程,wordpress 主题插件?
- ios - Xamarin Forms 中的 VNDocumentCameraViewController 冻结
- javascript - iOS 14 WKWebView 正文滚动问题
- php - 为什么我的 PHP 电子邮件表单发送的是空白电子邮件
- arrays - 使用 Object.keys 方法将获取的异步数据添加到数组的问题?