Experimento problemas en los que quiero redirigir la página según una lógica.
Entonces, si redirijo, debería ir a la página que estoy redirigiendo y no mostrar los componentes dentro de MyComponent .
La redirección ocurre, pero hay un retraso de 1 a 2 segundos.
Durante este período, hay una visualización del componente cuando no debería.
¿Hay alguna manera de prevenir esto y simplemente redirigir?
Nota: este componente se ha minimizado para centrarse en el problema. El componente real tiene mucho más que hacer allí.
El problema se puede observar en este proyecto mínimo. https://github.com/kvaithin/react-routing-issue
const MyComponent = () => {
const [data, setData] = useState();
// just a temp call to emulate getting data
useEffect(() => {
fetch("https://api.npms.io/v2/search?q=react")
.then((response) => response.json())
.then((d) => setData(d));
}, []);
// i want this redirect to happen without seeing the text below.
useEffect(() => {
const redirect = true;
if (redirect) {
// some other logic that will determine if redirect = true
window.location.replace("https://hn.algolia.com/api/v1/search?query=redux");
}
}, []);
return (
<div>
I should never reach here cos of the redirect But I still see this text briefly for a second
or 2 before redirecting.
{/* other components inside here */}
</div>
);
};
export default MyComponent;
"La función pasada a useEffect se ejecutará después de que el procesamiento se confirme en la pantalla" . Si desea evitar que se muestre el contenido antes de ejecutar su lógica, puede usar un estado de checking como este:
const MyComponent = () => {
const [data, setData] = useState();
const [checking, setChecking] = useState(true);
useEffect(() => {
fetch("https://api.npms.io/v2/search?q=react")
.then((response) => response.json())
.then((d) => setData(d));
}, []);
useEffect(() => {
const redirect = true;
if (redirect) {
setChecking(false);
window.location.replace("https://hn.algolia.com/api/v1/search?query=redux");
}
}, []);
if (checking) return null; // or a loading message or component
return (
<div>
I should never reach here cos of the redirect But I still see this text briefly for a second
or 2 before redirecting.
</div>
);
};
export default MyComponent;