React Hooks - useEffect()运行两次,因为依赖状态未定义



在下面的代码中,第二次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]);

return 未定义,如

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]);

最新更新