[英]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
.我在将请求推送到服务器的按钮上有一个 onClick 事件,并且应该在提交后返回主页,我尝试在该组件上使用 Reactjs useHistory 挂钩,但是我不断收到错误
TypeError: Object(...) is not a function
。
I need help to get around it我需要帮助来解决它
Are you using react-router: 5.1.0 ?你在使用react-router: 5.1.0吗?
useHistory
and other hooks didn't become available until then. useHistory
和其他钩子直到那时才可用。 I was getting the same error as OP using the simplest implementation and then realized I was only on react-router: 5.0.0
我使用最简单的实现遇到与 OP 相同的错误,然后意识到我只在
react-router: 5.0.0
Not sure if you are only using the react library but useHistory is part of react-router library.不确定您是否只使用 react 库,但 useHistory 是 react-router 库的一部分。 https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/hooks.md
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.在 React 类中使用 useHistory() 钩子时。 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:相反,您最好将
withRouter
高阶组件用于类或context
API,请参阅链接。基本示例如下:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.