如何在React中基于react-router v4实现页面返回功能
React Router v4 页面返回功能实现方案
你遇到的this.props.history为undefined的问题,本质是使用Route的render属性时,路由不会自动向组件注入history、location、match这些核心路由props,而用component属性的组件会自动获得这些props。下面给你两种可行的解决办法:
方法一:手动传递路由props到子组件
在定义Route的render函数时,把路由自带的props(也就是render的回调参数)解构传递给你的组件:
<HashRouter> <Switch> <Route exact path='/' component={Main}/> <Route path='/secondview' component={SecondView}/> {/* 修改render回调,接收routerProps并传递给子组件 */} <Route path='/traineeships' render={(routerProps)=> ( <Traineeship {...routerProps} rootState={this.state} setRootState={this.setState.bind(this)} /> )}/> <Route path='/information-filter' render={(routerProps)=> ( <InformationFilter {...routerProps} rootState={this.state} setRootState={this.setState.bind(this)} /> )}/> <Route path='/find-work' render={(routerProps)=> ( <FindWork {...routerProps} rootState={this.state} setRootState={this.setState.bind(this)} /> )}/> <Route path='/information-job' render={(routerProps)=> ( <InformationJob {...routerProps} rootState={this.state} setRootState={this.setState.bind(this)} /> )}/> <Redirect from='*' to='/' /> </Switch> </HashRouter>
之后在你的子组件里,就可以正常调用this.props.history.go(-1)实现返回了:
// 比如在Traineeship组件中 class Traineeship extends React.Component { handleBack = () => { // 调用返回上一页,和history.back()效果一致 this.props.history.go(-1); }; render() { return ( <button onClick={this.handleBack}>返回上一页</button> ); } }
方法二:用withRouter高阶组件注入路由props
如果你不想手动传递props,可以用React Router提供的withRouter高阶组件,它会把路由相关props注入到任意组件中:
步骤1:导入withRouter
import { withRouter } from 'react-router-dom';
步骤2:用withRouter包裹你的组件
class Traineeship extends React.Component { handleBack = () => { this.props.history.go(-1); }; render() { return ( <button onClick={this.handleBack}>返回上一页</button> ); } } // 用withRouter包裹组件后导出 export default withRouter(Traineeship);
这种方法不需要修改路由配置,不管你的组件是通过component还是render方式渲染,都能拿到history等路由props。
补充说明
history.go(-1)和history.back()效果完全一致,都是返回上一页,你可以根据习惯选择。- 如果你的组件是函数组件,同样可以用
withRouter包裹,用法和类组件一致(React Router v4中函数组件没有内置路由hooks,v5及以上才有useHistory等hooks)。
内容的提问来源于stack exchange,提问作者Mizlul
相关产品推荐
相关产品推荐

