react-router-dom 4.3.1中useHistory报TypeError错误求助
解决react-router-dom 4.3.1中useHistory不存在的报错
你遇到的报错是因为useHistory是react-router-dom v5及以上版本才新增的Hook,而你使用的4.3.1版本根本没有这个API,所以会提示“不是函数”。
针对4.3.1版本,有两种常用的方式实现返回上一页的功能:
1. 用withRouter高阶组件注入history
如果你的组件不是直接由<Route>渲染的(也就是props里没有history),可以用withRouter把组件包裹起来,它会把history、location、match这些路由相关的属性注入到组件props里:
import { NavLink, withRouter } from 'react-router-dom'; // 函数组件示例 const BackButton = ({ history }) => { const goBackToPreviousPage = () => { history.goBack(); }; return ( <button onClick={goBackToPreviousPage}> Back to previous page </button> ); }; // 用withRouter包裹后导出 export default withRouter(BackButton);
如果是类组件,写法类似:
import { Component } from 'react'; import { NavLink, withRouter } from 'react-router-dom'; class BackButton extends Component { goBackToPreviousPage = () => { this.props.history.goBack(); }; render() { return ( <button onClick={this.goBackToPreviousPage}> Back to previous page </button> ); } } export default withRouter(BackButton);
2. 直接从路由组件的props获取history
如果你的组件是通过<Route>直接渲染的(比如<Route path="/" component={YourComponent} />或者<Route path="/" render={props => <YourComponent {...props} />} />),那组件的props里已经自带history对象,直接解构使用就行:
import { NavLink } from 'react-router-dom'; const YourComponent = ({ history }) => { const goBackToPreviousPage = () => { history.goBack(); }; return ( <button onClick={goBackToPreviousPage}> Back to previous page </button> ); };
内容的提问来源于stack exchange,提问作者3gwebtrain
相关产品推荐
相关产品推荐

