代码之家  ›  专栏  ›  技术社区  ›  Mizlul

如何在react中执行返回函数[重复]

  •  0
  • Mizlul  · 技术社区  · 7 年前

    我正在使用 反应路由器 我想执行一些返回功能。

    我当前的代码如下:

    <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) 在其他组件上,但我得到了未定义的错误。

    在我的情况下,有人知道如何执行返回函数吗?

    2 回复  |  直到 7 年前
        1
  •  2
  •   Evgeny Timoshenko    7 年前

    你可以用 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

        2
  •  0
  •   GibboK    7 年前

    取决于 react-router (在本例中为3.0)您可以启用 BrowserHistory first 然后做:

    const BrowserHistory = require('react-router/lib/BrowserHistory').default;
    

    您可以在JSX中使用它:

    <button onClick={BrowserHistory.goBack}>Back</button>
    

    应用程序文件中的以下代码:

    <Router history={BrowserHistory}>
        <Route path="/" component={App} />
    </Router>