[英]React Hooks useEffect saves the last state and won't update it with the new one. It runs twice with two different states
[英]React Hooks - useEffect() runs twice because state of a dependency is undefined
在下面的代码中,第二个 useEffect() 运行了两次——一次是在employee
未定义时,另一次是在employee
有值时。
const [employee, setEmployee] = useState<Employee | undefined>(undefined);
const [buttonDisabled, disableButton] = useState<boolean>(true);
useEffect(() => {
// Run some fetch requests and then set employee state
setEmployee(employee);
}, []);
useEffect(() => {
const employeeId = employee.Id;
// Run some fetch requests and then set buttonDisabled state
disableButton(false);
// buttonDisabled is passed to a child component as a prop.
}, [employee]);
我如何确保第二个 useEffect() 只运行一次,并且只在employee
有值时运行。
const [employee, setEmployee] = useState<Employee | undefined>(undefined);
const [buttonDisabled, disableButton] = useState<boolean>(true);
useEffect(() => {
// Run some fetch requests and then set employee state
setEmployee(employee);
}, []);
useEffect(() => {
if (employee) {
const employeeId = employee.Id;
// Run some fetch requests and then set buttonDisabled state
disableButton(false);
// buttonDisabled is passed to a child component as a prop.
}
}, [employee]);
当 employee未定义时返回,像这样
const [employee, setEmployee] = useState<Employee | undefined>(undefined);
const [buttonDisabled, disableButton] = useState<boolean>(true);
useEffect(() => {
// Run some fetch requests and then set employee state
setEmployee(employee);
}, []);
useEffect(() => {
if(!employee)return;
const employeeId = employee.Id;
// Run some fetch requests and then set buttonDisabled state
disableButton(false);
// buttonDisabled is passed to a child component as a prop.
}, [employee]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.