我通过制作游戏项目来学习 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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)