当我尝试设置状态时出现错误。 错误:重新渲染次数过多。 React限制了渲染次数以防止无限循环。
const Money= (props) => {
// some states and functions
.
.
/
const [loss, setLoss] = useState('');
const [gain, setGain] = useState('');
const diffrenceInCount = (todayCount as any) - (yestarDayCount as any);
// (todayCount(6) and yestarDayCount(24) are my some states which holds the respective values)
//diffrenceInCount = -18
if (diffrenceInCount < 0) {
const moneyLoss = diffrenceInCount.toString();
setLoss(moneyLoss );
}
if (diffrenceInCount > 0) {
const moneyGain = diffrenceInCount.toString();
setGain(moneyGain);
}
useEffect(() => {
userMoney();
allUserMoney();
}, [])
return (
<IonContent>
{* some code *}
</IonContent>
);
}
export default Money;
我已经用useReducer
进行过尝试,并且正在寻找一种设置状态的解决方案。
答案 0 :(得分:0)
useEffect(() => {
if (diffrenceInCount < 0) {
const moneyLoss = diffrenceInCount.toString();
setLoss(moneyLoss );
}
if (diffrenceInCount > 0) {
const moneyGain = diffrenceInCount.toString();
setGain(moneyGain);
}
}, [diffrenceInCount]);
您应该尝试一下...仅在diffrenceInCount
中有更改时才运行