我在我的项目中使用React Ionic框架。我将离子切换组件的状态从Api调用的结果设置为true。当我这样做时,离子切换的onIonChange已经从状态设置为true,在页面重新加载时不必要地被触发。我到处寻找答案,其中大多数都是关于角离子的。下面是我的代码。让我知道我怎样才能阻止这种情况的发生。
import { IonToggle, IonItem, IonLabel } from '@ionic/react';
import { useEffect, useState } from 'react';
import { apiUrl } from '../../utils/apiUrl';
import Cookies from 'universal-cookie';
const sample: React.FC = () => {
const [covidDetails, setCovidDetails] = useState<{
firstDose?: boolean,
secondDose?: boolean
}>({
firstDose: false,
secondDose: false
});
const getCovidVaccine = async () => {
try {
const response = (await axios.get(`${apiUrl()}/user/getCovidVaccineDetails/{userIdfromcookie}`, {
headers: {
Authorization: `Bearer ${cookies.get('token')}`
}
})).data;
if (response.covidVaccine !== null) {
setFirstLoad(true);
setCovidDetails({
firstDose: response.covidVaccine.firstDose,
secondDose: response.covidVaccine.secondDose
})
}
} catch (error) {
console.log(error);
}
}
//this code fires on pageload if the checked for ion-toggle is true.
const setCovidVaccine = async (e) => {
try {
console.log("first", covidDetails);
var details = { firstDose: covidDetails.firstDose, secondDose: covidDetails.secondDose };
if (e.detail.value === "firstDose") {
details.firstDose = e.detail.checked;
}
if (e.detail.value === "secondDose") {
details.secondDose = e.detail.checked;
}
const response = (await axios.post(`${apiUrl()}/user/setCovidVaccineDetails/{userIdfromcookie}`, details, {
headers: {
Authorization: `Bearer ${cookies.get('token')}`
}
})).data;
if (response.covidVaccine !== null) {
setCovidDetails({
firstDose: response.covidVaccine.firstDose,
secondDose: response.covidVaccine.secondDose
})
}
} catch (error) {
console.log(error);
}
}
useEffect(() => {
getCovidVaccine();
}, []);
return (
<div>
<IonItem>
<IonLabel className={styles.vaccineLabel}>
<p>1st Dose Vaccine</p>
</IonLabel>
<IonToggle
color="primary"
checked={covidDetails.firstDose}
value="firstDose"
onIonChange={e => setCovidVaccine(e)}
/>
</IonItem>
<IonItem>
<IonLabel className={styles.vaccineLabel}>
<p>2nd Dose Vaccine</p>
</IonLabel>
<IonToggle
color="primary"
checked={covidDetails.secondDose}
value="secondDose"
onIonChange={e => setCovidVaccine(e)}
/>
</IonItem>
</div>
);
我刚刚遇到了同样的问题,也只发现了这个线程。
我解决了这个问题绑定onIonChange召回只有在初始数据已经加载。应该是
const [loaded, setLoaded] = useState(false);
const setCovidVaccine = async (e) => {
...
setLoaded(true);
}
return (
<IonToggle
color="primary"
checked={covidDetails.secondDose}
value="secondDose"
{...(loaded ? { onIonChange: setCovidVaccine} : {})}
/>
);