我试图从useEffect钩子内部调用函数'handleSaveGeneral'
const ProfilePage = (props) => {
const [uneligible, setUneligible] = React.useState(false);
useEffect(() => {
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);
};
});
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>
);
};
'save'按钮也没有无故渲染,当我们点击'save'时,我试图显示警报,但函数'handleSaveGeneral'在问题的代码沙箱中给我未定义
https://codesandbox.io/s/modest-field-xqf91?file=/src/App.js: 257 - 274
const
声明为块作用域
所以你应该在useEffect
之外定义handleSaveGeneral
函数并在内部调用它,这样其他组件就可以访问它
更新:确保在useEffect的依赖项中添加了一个数组,以避免无限循环
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()
},[]);
这里是整个代码
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;
标题>