You don't actually need state here. Just use const uneligible = age<18
and get rid of the useState
code, and it will work okay. If you put uneligible
in the state you create a render loop, as setting it triggers a re-render, which sets the state again and triggers another re-render, etc.
const ProfilePage = (props) => {
var dateOfBirth = "2007-01-01";
var split_dob = dateOfBirth.split("-");
var month = split_dob[1];
var day = split_dob[2];
var year = split_dob[0];
var dob_asdate = new Date(year, month, day);
var today = new Date();
var mili_dif = Math.abs(today.getTime() - dob_asdate.getTime());
var age = mili_dif / (1000 * 3600 * 24 * 365.25);
console.log(age);
const uneligible = age < 18;
return (
<div>
{uneligible && (
<Alert variant="filled" severity="error">
This is an error alert — check it out!
</Alert>
)}
</div>
);
};
Sandbox example
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…