javascript - React - Axios 调用发出过多请求
问题描述
我通过制作游戏项目来学习 React 和 Redux。我想通过 API 获取数据(属性),但它会导致太多的请求。猜猜它可以直接在功能性反应组件中放置 axios 调用,但我不知道如何修复它。
function Attributes({ attributes, dispatch }) {
axios.get(`/api/heroes/1/get-attributes`).then(res => {
dispatch(AttribAction.set(objectToArray(res.data)));
});
return (
<div className="content">
{attributes.map((attrib, index) => (
<div
key={index}
className={attrib.id == null ? "attrib-block empty" : "attrib-block"}
>
<p>
<strong>{attrib.name}</strong>: {attrib.value}
</p>
<div>
<button
className="attrib-button"
onClick={() => dispatch(AttribAction.increment(attrib.id))}
>
+
</button>
<button
className="attrib-button"
onClick={() => dispatch(AttribAction.decrement(attrib.id))}
>
-
</button>
</div>
</div>
))}
</div>
);
}
解决方案
将代码放入 useEffect 钩子中,然后传入一个数组作为第二个参数,以指定哪些变量应使其在更改时重复效果。一个空数组表示永远不要重复它。
import React, { useEffect } from 'react';
function Attributes({ attributes, dispatch }) {
useEffect({
axios.get(`/api/heroes/1/get-attributes`)
.then(res => {
dispatch(AttribAction.set(objectToArray(res.data)));
});
}, []);
// ... etc
}
推荐阅读
- python - Selenium 的 Python Web 爬虫索引错误
- protractor - 将chrome版本和chrome驱动版本更新到80后,出现inspector detached event错误
- php - 如何在 PHP 中从主数组中拆分或获取子数组的值
- mysql - 使用 VB Net 在 mySQL 8.0.19 上连接到我的数据库
- python-3.x - 使用 Python 提取区域路径中的所有变更集
- java - REST 简单配置问题(Servlet 容器 4.0 和 JAX-RS 2.1)
- python-3.x - 为什么`for k in [*dictionary]`分配k?
- c# - 替换 HTML 字符串以导出为 PDF 的安全方法
- angular - 如何为 ngModel 设置默认值
- python - 如何在 Python 中将不正确的日期时间格式从原始 csv 文件更改为正确的日期时间格式