【问题标题】:How to perform go back function in React [duplicate]如何在 React 中执行返回功能 [重复]
【发布时间】:2018-11-07 19:46:41
【问题描述】:

我正在使用 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),但我遇到了未定义的错误。

有谁知道在我的情况下如何执行返回功能?

【问题讨论】:

标签: javascript reactjs react-native react-router-v4


【解决方案1】:

如果你需要访问历史对象,你可以使用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】:

    根据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>
    

    【讨论】:

    • 我收到错误:找不到模块“react-router/lib/BrowserHistory”
    • @Mizlul 我没有注意到您使用的是 v4 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 1970-01-01
    相关资源
    最近更新 更多