简体   繁体   中英

TypeError: Object(...) is not a function when using useHistory() hooks

i have an onClick event on a button that pushes requests to a server and should go back to the homepage afetr submitting , i tried to use the Reactjs useHistory hooks on that component ,however i keep getting the error TypeError: Object(...) is not a function .

I need help to get around it

Are you using react-router: 5.1.0 ? useHistory and other hooks didn't become available until then. I was getting the same error as OP using the simplest implementation and then realized I was only on react-router: 5.0.0

Not sure if you are only using the react library but useHistory is part of react-router library. https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/hooks.md

If adding the react-router not fix the issue. Please add some code so we can help.

You can see this error

TypeError: Object(…) is not a function

when using useHistory() hooks in React class. You are not supposed to do it. Instead you are better to use the withRouter high-order component for class or context API, see link .The basic example is like this:

import React from 'react';
import { withRouter } from 'react-router-dom';

class MyClass extends React.Component {
  ...

  handleEvents = (e) => this.props.history.push('another-route')

  render(){
    return <div onClick={e => handleEvents(e)}>Hello World!</div>
  }
}

const MyClassWithRouter = withRouter(MyClass)
export MyClassWithRouter 

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