简体   繁体   中英

'TypeError: Cannot read properties of undefined (reading 'push')' when using 'useHistory' hook of 'react-router-dom'

I'm trying to use the "useHistory" hook from 'react-router-dom' and I come across the error, ' TypeError: Cannot read properties of undefined (reading 'push') '. Below is my code.

import './App.css';
import { React, useState } from 'react'
import Header from './Header';
import Register from './Register';
import Login from './Login';
import { BrowserRouter as Router, Switch, Route, useHistory } from 'react-router-dom'

function App() {
  const [ loggedIn, setLoggedIn ] = useState(false)
  const history = useHistory()

  return (
    <Router>
      <Header />
      <Switch>
        <Route exact path='/'>
          {loggedIn ? <h1>Logged In</h1> : <Register setLoggedIn={setLoggedIn} />}
        </Route>
        <Route path='/log-in'>
          {loggedIn ? () => history.push('/') : <Login setLoggedIn={setLoggedIn} loggedIn={loggedIn} />}
        </Route>
      </Switch>
    </Router>
  );
}

export default App;

Why is 'history.push' causing this error within my ternary operator?

import { React, useState } from 'react'
import { BrowserRouter as Router, Switch, Route, useHistory } from 'react-router-dom'
import Login from './login';

function App() {
  return (
    <Router>
      <Switch>
        <Route path='/log-in'>
         <Login/>
        </Route>
      </Switch>
    </Router>
  );
}

export default App;

import { useEffect, useState } from "react"
import { useHistory } from "react-router-dom"

const Login=()=>{
  const history=useHistory()
  const [loggedin,setloggedin]=useState(true)
  useEffect(()=>{
    if(!loggedin){
      history.push("/")
    }
  },[loggedin])
  return(
    <div>login</div>
  )
}
export default Login

In your code, the code inside your route only will be executed that is

{loggedIn ? () => history.push('/') : <Login setLoggedIn={setLoggedIn} loggedIn={loggedIn} />}

In which the code inside your app component will not be executed. You can try the above code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM