Quiero conectar la flecha hacia arriba y hacia abajo para cambiar las secciones, y con ella cambiar la URL con useHistory, pero aparece este error "Pages.jsx: 15 Uncaught TypeError: no se pueden leer las propiedades de undefined (leyendo 'push')" Ps ahora solo quiero verificar si esto registrará y cambiará la URL
Código a continuación
import {Route, Router, useHistory} from 'react-router-dom' import Section1 from "./Pages/Section1"; import Section2 from "./Pages/Section2"; import '../css/Pages.css' const Pages = () =>{ const [count, setCount] = useState(0) const urls = ['/home', '/about', '/story'] const history = useHistory() useEffect(() => { const keyCheck = (event) => { if(event.keyCode === 40){ console.log('arrow down'); setCount(count-1) history.push(urls[count]) } else if (event.keyCode === 38){ console.log('arrow up'); setCount(count+1) history.push(urls[count]) } } window.addEventListener('keydown', keyCheck); return () => { window.removeEventListener('keydown', keyCheck); }; }, [count]) return( <div id="fullPage"> {/*<Router> <Route path='/report' component={Section2}/> </Router> */} </div> ) } export default PagesDebe envolver el componente principal en el enrutador. O mueva la lógica useHistory a un componente secundario y coloque el componente secundario dentro del fragmento del enrutador.
¡El enrutador proporciona el contexto para useHistory!
const Pages = () =>{ return( <div id="fullPage"> <Router> <RouterWithKeyNavigation /> </Router> </div> ) }Luego, este archivo será envuelto por el componente del enrutador de react-router-dom
const RouterWithKeyNavigation = () => { const [count, setCount] = useState(0) const urls = ['/home', '/about', '/story'] const history = useHistory() useEffect(() => { const keyCheck = (event) => { if(event.keyCode === 40){ console.log('arrow down'); setCount(count-1) history.push(urls[count]) } else if (event.keyCode === 38){ console.log('arrow up'); setCount(count+1) history.push(urls[count]) } } window.addEventListener('keydown', keyCheck); return () => { window.removeEventListener('keydown', keyCheck); }; }, [count]) return (<Route path='/report' component={Section2}/>) }