Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

635
Views
Debe llamar a navegar () en un React.useEffect (), no cuando su componente se procesa por primera vez

Soy nuevo en ReactJS. En la carga inicial de la página, quiero verificar si el state es nulo, luego quiero redirigir a otra login Page

Aquí está el código del componente:

 export default function Addblousesalwar() { const navigate = useNavigate(); const { state } = useLocation(); console.log(state) //null if(state === null || state === undefined){ navigate("/login") }

Pero muestra error:

 You should call navigate() in a React.useEffect(), not when your component is first rendered.

Probé a través de useEffect también. Pero useEffect no se ejecuta.

 useEffect(() => { if(state === null || state === undefined){ navigate("/") } }, []); useEffect(() => { if(state === null || state === undefined){ navigate("/") } }, []);

Probé esto también

 useEffect(() => { if(state === null || state === undefined){ navigate("/") } }, [state]);

Este efecto de uso tampoco se activa Por favor, ayúdenme con algunas soluciones

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

debe usar useEffect después de todas las funciones asíncronas, aquí el ejemplo:

 const userInfo = localStorage.getItem('user-info'); async function signUp() { let item = {name, password, email}; console.warn(item); let result = await fetch("http://127.0.0.1:8000/api/register",{ method: 'POST', body: JSON.stringify(item), headers: { "content-type": 'application/json', "Accept": 'application/json'} }) result = await result.json(); console.warn('result', result); localStorage.setItem("user-info",JSON.stringify(result)); navigate("/add"); } useEffect(() => { if (userInfo){ navigate("/add") } },[])
about 4 years ago · Juan Pablo Isaza Report

0

Como se menciona en los comentarios, realmente debería proporcionar un codeandbox o al menos más código.

Habiendo dicho eso, voy a adivinar que 'estado' no es indefinido ni es nulo, es un [] (eso es lo que suele ser predeterminado para const [state, setState] = useState([]) ) y es por eso que piensas no funciona.

probar

 useEffect(() => { if(!state.length){ navigate("/") } }, []);
about 4 years ago · Juan Pablo Isaza Report

0

export default function Addblousesalwar() { const navigate = useNavigate(); const { state } = useLocation(); //I used useLayoutEffect instead of useEffect and the below turned into warning instead of an error //You should call navigate() in a React.useEffect(), not when your component is first rendered. useLayoutEffect(() => { if(state === null || state === undefined){ navigate("/") } }, []); }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!