具有许多依赖项的 useEffect
useEffect with many dependencies
我正在尝试招募员工,这是我正在尝试使用 useEffect
进行的操作
function AdminEmployees() {
const navigate = useNavigate();
const dispatch = useDispatch();
// fetching employees
const { adminEmployees, loading } = useSelector(
(state) => state.adminFetchEmployeeReducer
);
useEffect(() => {
dispatch(adminFetchEmployeeAction());
if (adminEmployees === "unAuthorized") {
navigate("/auth/true/false");
}
}, [adminEmployees, navigate,dispatch]);
console.log("Here i am running infinie loop");
console.log(adminEmployees);
return (
<>
{loading ? (
<Loader></Loader>
) : adminEmployees === "no employees" ? (
<h1>No Employees</h1>
) : (
<>
{adminEmployees &&
adminEmployees.map((employee) => {
return (
<div className="admin__employee__container" key={employee.id}>
<AdminSingleEmployee
employee={employee}
></AdminSingleEmployee>
</div>
);
})}
</>
)}
</>
);
}
这里我想实现2个目标:
- 获取 adminEmployees
- if (adminEmployees==='unAuthorized') 然后去登录页面
但是当按照代码执行此操作时,它会创建无限循环。
我怎样才能实现所需的功能?
简单的肮脏路径:将 useEffect
拆分为 2
useEffect(() => {
if (adminEmployees === "unAuthorized") {
navigate("/auth/true/false");
}
}, [adminEmployees, navigate]);
useEffect(() => {
dispatch(adminFetchEmployeeAction());
}, [dispatch]);
更好的方法:在 reducer 或 action creator 中处理这种情况,在 store 中翻转标志,然后在组件中使用它:
const { shouldNavigate } = useSelector(state => state.someSlice);
useEffect(() => {
if(shouldNavigate) {
// flipping flag back
dispatch(onAlreadyNavigated()));
navigate("/yourPath...");
},
[navigate, dispatch, shouldNavigate]
);
我正在尝试招募员工,这是我正在尝试使用 useEffect
function AdminEmployees() {
const navigate = useNavigate();
const dispatch = useDispatch();
// fetching employees
const { adminEmployees, loading } = useSelector(
(state) => state.adminFetchEmployeeReducer
);
useEffect(() => {
dispatch(adminFetchEmployeeAction());
if (adminEmployees === "unAuthorized") {
navigate("/auth/true/false");
}
}, [adminEmployees, navigate,dispatch]);
console.log("Here i am running infinie loop");
console.log(adminEmployees);
return (
<>
{loading ? (
<Loader></Loader>
) : adminEmployees === "no employees" ? (
<h1>No Employees</h1>
) : (
<>
{adminEmployees &&
adminEmployees.map((employee) => {
return (
<div className="admin__employee__container" key={employee.id}>
<AdminSingleEmployee
employee={employee}
></AdminSingleEmployee>
</div>
);
})}
</>
)}
</>
);
}
这里我想实现2个目标:
- 获取 adminEmployees
- if (adminEmployees==='unAuthorized') 然后去登录页面
但是当按照代码执行此操作时,它会创建无限循环。
我怎样才能实现所需的功能?
简单的肮脏路径:将 useEffect
拆分为 2
useEffect(() => {
if (adminEmployees === "unAuthorized") {
navigate("/auth/true/false");
}
}, [adminEmployees, navigate]);
useEffect(() => {
dispatch(adminFetchEmployeeAction());
}, [dispatch]);
更好的方法:在 reducer 或 action creator 中处理这种情况,在 store 中翻转标志,然后在组件中使用它:
const { shouldNavigate } = useSelector(state => state.someSlice);
useEffect(() => {
if(shouldNavigate) {
// flipping flag back
dispatch(onAlreadyNavigated()));
navigate("/yourPath...");
},
[navigate, dispatch, shouldNavigate]
);