const EmailSelection: React.FC<{emails: EmailDataType[] | undefined}> = ({emails}) => {
const [emailsCopy, setEmailsCopy] = useState<EmailDataType[] | undefined>(emails);
const [defaultEmail2, setDefaultEmail2] = useState<string>();
useLayoutEffect(() => {
setDefaultEmail2(emailsCopy?.find(email => email.isDefault)?.email);
}, [emailsCopy])
const changeDefaultEmail = ((selectedEmail: string) => {
const emailsCopy2 = emailsCopy?.map(email => {
return email.email === selectedEmail ? { ...email, isDefault: true }
: { ...email, isDefault: false }
});
setEmailsCopy(emailsCopy2);
});
return (
<IonPage >
<IonContent className={[style['main-content'], 'ion-padding'].join(' ')} >
<IonRadioGroup
value={defaultEmail2}
onIonChange={e => changeDefaultEmail(e.detail.value)}>
{emailsCopy?.map((email) => {
return (
<IonItem key={email.email} lines='none' className='ion-margin-start'>
<IonLabel>{email.email}</IonLabel>
<IonRadio slot='start' value={email.email} />
</IonItem>
);
})}
</IonRadioGroup>
</IonContent>
</IonPage>
);
};
export default EmailSelection;
方法changeDefaultEmail在单选按钮onChange事件上执行。由于某种原因,这会在此函数和useLayoutEffect之间启动无限循环。我不知道为什么。
我在这个问题上苦苦挣扎了很长时间!
答案 0 :(得分:0)
这是循环: useLayoutEffect->更改defaultEmail2->触发单选onChange-> 调用changeDefaultEmail->更改emailsCopy->再次触发userLayoutEffect