const
declaration is bloc-scope
So you should define the handleSaveGeneral
function outside of useEffect
and call it inside, so that other components can get access to it
update:
Make sure you add an array to useEffect's dependency to avoid infinite loop
const handleSaveGeneral = (e) => {
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);
setUneligible(age < 18);
};
useEffect(() => {
handleSaveGeneral()
},[]);
here is the whole code
import React, { useEffect } from "react";
import Button from "react-bootstrap/Button";
import Alert from "@material-ui/lab/Alert";
const ProfilePage = (props) => {
const [uneligible, setUneligible] = React.useState(false);
const handleSaveGeneral = (e) => {
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);
setUneligible(age < 18);
};
useEffect(() => {
handleSaveGeneral()
},[]);
return (
<div>
<Button variant="outline-primary" onClick={handleSaveGeneral}>
Save
</Button>
{uneligible && (
<Alert variant="filled" severity="error">
This is an error alert — check it out!
</Alert>
)}
</div>
);
};
export default ProfilePage;
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…