Con el riesgo de ser una pregunta duplicada, porque estoy seguro de que se ha hecho varias veces, como se ve enesta publicación popular. Tengo este caso cuando quiero verificar primero si está autenticado y, si no, debería omitir el resto de los cálculos.
¿Cómo puedo utilizar useEffect o algún otro enlace para este problema, dado el siguiente código?
React Hook "useDispatch" is called conditionally. React Hooks must be called in the exact same order in every component render. React Hook "useSelector" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return? React Hook "useEffect" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?
Componente
export const DoSomething: FunctionComponent = () => { const isAuthenticated = useSelector<State, boolean>((state) => state.isAuthenticated); if (isAuthenticated === false) { return <Navigate to='/login' /> } const dispatch = useDispatch(); const { initialDay: initialDay = '0' } = useParams(); useEffect(() => { // Do another thing here dispatch(foo()); }, [dispatch]); return ( ... ) }
Traté de envolver con una declaración if...else como esta:
if (isAuthenticated){ const dispatch = useDispatch(); const { initialDay: initialDay = '0' } = useParams(); useEffect(() => { // Do another thing here dispatch(foo()); }, [dispatch]); }
pero el problema aun persiste
Si devuelve algo antes de que se invoque el gancho, se rompen las reglas del gancho . Si desea verificar alguna condición, colóquela dentro de la devolución de llamada, garantiza que el enlace se llame correctamente en cada renderizado.
export const DoSomething: FunctionComponent = () => { const isAuthenticated = useSelector<State, boolean>((state) => state.isAuthenticated); const dispatch = useDispatch(); const { initialDay: initialDay = '0' } = useParams(); useEffect(() => { if (isAuthenticated === false) { return; } else { dispatch(foo()); } }, [dispatch]); if (isAuthenticated === false) { return <Navigate to='/login' /> } return ( ... ) }