我从后端获得了一些价值,但我想将它们转换为前端。 我做了一个开关,但是,它给出了出现在标题中的错误。 我也尝试过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>
</>
)
}
答案 0 :(得分:1)
1-使用这种方法,您在组件渲染时调用setAppCode()
。由于它是useState
函数,因此可以重新渲染组件。然后它重新渲染并再次调用setAppCode()
(无限循环)。
2-(请明确说明)由于您使用的是http请求,因此如果您提出要求,则只能从后端获取通知。您只问一次(组件呈现的时刻(使用useEffect))。为了使通知动态更新,您应该使用一些pushNotifications系统。
3-您的notify变量是一个数组。因此,您不能只访问属性通知。您需要访问数组内部的一个对象,在我的示例中,我将访问第一个对象。
要解决此问题,我将在API请求后调用您的switch语句:
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;
}
})
Espero ter ajudado:)
答案 1 :(得分:0)
我创建了一个按参数接收值的函数,并使用该值来分析哪个类别适合
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>
</>
)
}
答案 2 :(得分:0)
使用switch
触发器将useEffect
块包裹在[notify]
之外
useEffect(()=> notify &&
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;
},[notify])