[英]React - Axios call make too many requests
我通过制作游戏项目来学习 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
}
您可以使用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)));
});
}, [])
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>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.