首页 > 解决方案 > 如何在 React 中执行返回功能

问题描述

我正在使用react-router v.4,我想执行一些返回功能。

我当前的代码如下所示:

<HashRouter>
       <Switch>
            <Route exact path='/' component={Main}/>
            <Route path='/secondview' component={SecondView}/>
            <Route path='/traineeships' render={()=>(<Traineeship rootState={this.state} setRootState={this.setState.bind(this)} />)}/>
            <Route path='/information-filter' render={()=>(<InformationFilter rootState={this.state} setRootState={this.setState.bind(this)} />)}/>
            <Route path='/find-work' render={()=>(<FindWork rootState={this.state} setRootState={this.setState.bind(this)} />)}/>
            <Route path='/information-job' render={()=>(<InformationJob rootState={this.state} setRootState={this.setState.bind(this)} />)}/>
            <Redirect from='*' to='/' />
       </Switch>

this.props.history.go(-1)在其他组件上尝试了几个选项,但我得到了未定义的错误。

任何人都知道如何在我的情况下执行返回功能?

标签: javascriptreactjsreact-nativereact-router-v4

解决方案


withRouter如果您需要访问历史对象,您可以使用:

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

class SecondView extends React.Component {
  render() {
    return (
      <button onClick={() => this.props.history.go(-1)} />
    )
  }
}

const SecondViewnWithRouter = withRouter(SecondView)

withRouter 将在渲染时将更新的匹配、位置和历史道具传递给包装的组件。

https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/api/withRouter.md


推荐阅读