javascript - 如何在 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)
在其他组件上尝试了几个选项,但我得到了未定义的错误。
任何人都知道如何在我的情况下执行返回功能?
解决方案
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 将在渲染时将更新的匹配、位置和历史道具传递给包装的组件。
推荐阅读
- python - 如何在python中向自定义dict子类添加类型注释?
- c++ - 让成员函数返回类型成为您要返回的实际对象的超类的正确方法是什么?
- excel - 如何在vba中配置行号?
- c# - GraphQL.NET 订阅不返回任何内容
- amazon-web-services - 使用查询编辑器在 Amazon Redshift 上创建数据库
- python - 如何使用 Python 3 创建 Virtualenv?
- php - Google 日历 API:来自事件的描述包含意外字符
- templates - 将文档插入模板时签名消失
- c# - EF Core 3 DbQuery 等效功能
- animation - 制作一张足以容纳子文本的卡片