Digamos que tengo estas rutas:
<Switch> <Route exact path="/myflix/:slug" component={Home} /> <Route exact path="/myflix/:slug/register" component={Signup} /> <Route exact path="/myflix/:slug/event" component={Event} /> <Route exact path="/myflix/:slug/contact" component={Contact} /> <Route exact path="/myflix/:slug/login" component={Login} /> <Route exact path="/myflix/:slug/show-details" component={ShowList} /> <Route exact path="/myflix/:slug/*" component={NotFound} /> <Route path="*" exact={true} component={NotFound} /> <Redirect to="/not-found" /> {/* <Route path="*" element={<NotFound />} /> */} </Switch>Tenemos ciertos slugs de una API, en esta forma:
[ { id: 1, title: "_flix", slug: "_flix", status: true, viewTime: null, langue: null, createdAt: "2021-06-24", updatedAt: null, }, { id: 9, title: "test_flix", slug: "test_flix", status: true, viewTime: null, langue: null, createdAt: "2021-06-24", updatedAt: null, }, { id: 10, title: "flix_2", slug: "flix_2", status: true, viewTime: null, langue: null, createdAt: "2021-06-24", updatedAt: null, }, ] Cuando hago un slug inválido, quiero redirigir a la página NotFound :
useEffect(() => { getSlug(slug) .then((res) => { const { id } = res.data; document.title = res.data.title; getSetting(id).then((result) => { setStyle(result.data); getLangue(id).then((res) => { setlang(res.data.langue); }); }); }) .catch((error) => (window.location.href = "/not-found")); }, [slug]); Utilicé el código anterior (ver .catch ), pero cuando hago un slug inválido, redirige la página no encontrada y actualiza la página. Necesito redirigir sin actualizar. ¿Alguna solución?
window.location.href efectivamente refresca la página. Dado que parece estar usando React Router Dom v5 , debería usar useHistory para hacer redirecciones. Aquí hay una descripción general de cómo lo usaría:
import { useHistory } from "react-router-dom"; function HomeButton() { let history = useHistory(); function handleClick() { history.push("/home"); } return ( <button type="button" onClick={handleClick}> Go home </button> ); } No está relacionado con useHistory o la redirección, pero podría optimizar ligeramente la configuración de sus rutas:
<Switch> <Route exact path="/myflix/:slug" component={Home} /> <Route exact path="/myflix/:slug/register" component={Signup} /> <Route exact path="/myflix/:slug/event" component={Event} /> <Route exact path="/myflix/:slug/contact" component={Contact} /> <Route exact path="/myflix/:slug/login" component={Login} /> <Route exact path="/myflix/:slug/show-details" component={ShowList} /> <Route path="*" component={NotFound} /> </Switch> El uso window.location.href = "/not-found" muta la ubicación actual y vuelve a cargar la página, es decir, volverá a montar toda la aplicación React. Utilice una redirección imperativa a la ruta "/not-found" .
import { useHistory } from 'react-router-dom'; ... const history = useHistory(); ... useEffect(() => { getSlug(slug) .then((res) => { const { id, title } = res.data; document.title = title; getSetting(id) .then((result) => { setStyle(result.data); }); getLangue(id) .then((res) => { setLang(res.data.langue); }); }) .catch((error) => { history.replace("/not-found"); // REPLACE = redirect }); }, [slug]); Representar una Route en path="/not-found" a la que se puede redirigir.
<Switch> <Route path="/myflix/:slug/register" component={Signup} /> <Route path="/myflix/:slug/event" component={Event} /> <Route path="/myflix/:slug/contact" component={Contact} /> <Route path="/myflix/:slug/login" component={Login} /> <Route path="/myflix/:slug/show-details" component={ShowList} /> <Redirect from="/myflix/:slug/*" to="/not-found" /> // <-- redirect unhandled paths <Route path="/myflix/:slug" component={Home} /> <Route path="/not-found" component={NotFound} /> // <-- render NotFound component route <Redirect to="/not-found" /> </Switch>