我在下面的代码中有两个问题,我需要来自社区的输入。
1.我收到React Hook useEffect has a missing dependency: 'medicationState.eligibilityResponse'. Either include it or remove the dependency array warning
警告,但当我在下面的useEffect()
数组中包含medicationState.EligibilityResponse
(而不是showBadge
)时,组件进入递归无限循环。
1.此外,药物始终显示为合格(即showBadge
设置为真),即使终点返回假。
社会人士会否就这些问题提供意见?
import React, { useEffect } from 'react';
import { GroupMed } from '../../../../state/ducks/medications/models';
import { medicationsActions } from '../../../../state/ducks/medications';
import { useDispatch, useSelector } from 'react-redux';
import { ApplicationState } from '../../../../state/ducks';
import {
ChaseJSON,
ExMedJSON,
FetchEligibilityRequest,
PrescriptionJSON,
} from '../../../../state/ducks/medications/types';
import { MedicationStatusProps } from './v2-recipes/medication-status';
export interface MedicationBadgeProps {
index: number;
groupMed: GroupMed;
}
const MedicationBadge: React.FC<MedicationStatusProps> = ({ index, groupMed }: MedicationBadgeProps) => {
const dispatch = useDispatch();
const medicationState = useSelector((state: ApplicationState) => state.medicationState);
let showBadge = false;
useEffect(() => {
if (!(medicationState.EligibilityResponse && medicationState.EligibilityResponse.data)) {
const groupMedItem = groupMed.groupMedItems[0];
const fetchEligibilityRequest: FetchEligibilityRequest = {
rxcui: groupMedItem.getRxcui(),
groupMedItemType: groupMedItem.item.groupMedItemType,
groupMedItemDrug:
(groupMedItem.item as ChaseJSON).drug ||
(groupMedItem.item as PrescriptionJSON).drug ||
(groupMedItem.item as ExMedJSON).externalMed.drug,
medicationSearchResult:
(groupMedItem.item as ChaseJSON).searchResult ||
(groupMedItem.item as ExMedJSON).externalMed?.healthProfileMedication?.searchResult,
};
dispatch(
medicationsActions.fetchEligibility(groupMedItem.getId(), fetchEligibilityRequest),
);
}
}, [dispatch, showBadge, groupMed.groupMedItems]);
if (medicationState.EligibilityResponse.data?.isEligible) {
showBadge = medicationState.EligibilityResponse.data?.isEligible;
}
if (showBadge) {
return (
<ui-section flowDirection="horizontal" spacingTop="mini">
<ui-icon imgClass="eligible" spacingRight="mini" style={{ marginLeft: '0px' }}></ui-icon>
</ui-section>
);
} else {
return <></>;
}
};
export default MedicationBadge;
1条答案
按热度按时间a64a0gku1#
像
dispatch
和setState
这样的函数是由React本身处理的,并且是稳定的,所以你不需要将它作为dep包括在内。至于showBadge
,在效果回调中看不到它的用法,所以你可能不需要它。medicationState.eligibilityResponse
应该包括在内。修改如下(假设
medicationsActions
是稳定动作的集合):如果循环不断出现,我会再次检查if条件是否正确。