TypeError:使用useHistory()挂钩时,Object(...)不是函数

时间:2020-03-09 02:12:32

标签: javascript reactjs redirect react-hooks

我在按钮上有一个onClick事件,该事件将请求推送到服务器,应该返回到提交后的首页,我尝试在该组件上使用Reactjs useHistory挂钩,但是我一直收到错误TypeError: Object(...) is not a function

我需要帮助来解决它

3 个答案:

答案 0 :(得分:1)

不确定是否仅使用react库,但useHistory是否是react-router库的一部分。 https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/hooks.md

如果添加react-router不能解决问题。请添加一些代码,以便我们提供帮助。

答案 1 :(得分:1)

您是否使用react-router: 5.1.0?直到那时useHistory和其他钩子才可用。我使用最简单的实现遇到了与OP相同的错误,然后意识到我只在react-router: 5.0.0

答案 2 :(得分:-1)

您可以看到此错误

TypeError: Object(…) is not a function

在React类中使用useHistory()钩子时。您不应该这样做。相反,您最好对类或withRouter API使用context高阶组件,请参见link。基本示例如下:

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