REACTJS错误:重新渲染过多.React限制渲染次数,以防止出现无限循环



我得到了一些值​​从后端,但我想将它们转换为前端。我做了一个开关,然而,它给出了这个错误,出现在标题中。我也尝试过if,但它给出了相同的错误。

如果你有其他方法,我也接受小费。

代码:

export default function Notification() {
const { guid } = useParams();
const [appcodeValue, setAppcodeValue] = useState(null);
const [notify, setNotify] = useState([]);
function fetchNotifications() {
setLoading(true);
api
.get(`/v1/admin/announcements/${guid}`)
.then(({ data: notifications }) => {
setNotify(notifications);
})
.catch(() => {
setError(`Desculpe, não foi possivel carregar a notificação.`);
})
.finally(() => {
setLoading(false);
});
}
useEffect(() => {
fetchNotifications();
}, []);
if (loading) {
return (
<Center>
<Loading size="40" />
</Center>
);
}
switch (notify.appcode) {
case 0:
return setAppcodeValue('Todos');
break;
case 1:
return setAppcodeValue('Associados');
break;
case 2:
return setAppcodeValue('Não Associados');
break;
default:
break;
}
return (
<>
<CardAppcode>
Appcode
{!loading && notify ? <p>{appcodeValue}</p> : []}
</CardAppcode>
</>
)
}

1-使用这种方法,您在组件渲染时调用setAppCode()。由于它是一个useState函数,因此会使组件重新渲染。然后它重新渲染并再次调用setAppCode()(无限循环(。

2-(只是为了明确一点(由于您使用的是http请求,因此只有当您提出请求时,才能从后端获得通知。您只询问一次(组件渲染的那一刻(使用useEffect((。为了实现通知的动态更新,您应该使用一些pushNotifications系统。

3-通知变量是一个数组。所以你不能只访问属性通知。您需要访问数组中的一个对象,在我的示例中,我将访问第一个对象。

为了解决这个问题,我只需要在API请求后调用您的开关语句:

api.get(`/v1/admin/announcements/${guid}`)
.then(({ data: notifications }) => {
setNotify(notifications);
switch (notify[0].appcode) {
case 0:
return setAppcodeValue('Todos');
break;
case 1:
return setAppcodeValue('Associados');
break;
case 2:
return setAppcodeValue('Não Associados');
break;
default:
break;
}
})

西班牙:(

我创建了一个函数,它通过参数接收值,并使用该值来分析哪些类别符合

export default function Notification() {
const { guid } = useParams();
const [appcodeValue, setAppcodeValue] = useState(null);
const [notify, setNotify] = useState([]);
function fetchNotifications() {
setLoading(true);
api
.get(`/v1/admin/announcements/${guid}`)
.then(({ data: notifications }) => {
setNotify(notifications);
})
.catch(() => {
setError(`Desculpe, não foi possivel carregar a notificação.`);
})
.finally(() => {
setLoading(false);
});
}
useEffect(() => {
fetchNotifications();
}, []);
if (loading) {
return (
<Center>
<Loading size="40" />
</Center>
);
}
function verifyValue(value) {
switch (value) {
case 0:
return 'Todos'
break;
case 1:
return 'Associados'
break;
case 2:
return 'Não Associados'
break;
default:
break;
}
}
return (
<>
<CardAppcode>
Appcode
{!loading && notify ? <p>{verifyValue(notify.appcode)}</p> : []}
</CardAppcode>
</>
)
}

相关内容

最新更新