路由跳转
引入依赖
1 | import { withRouter, RouteComponentProps } from 'react-router-dom'; |
组件继承上面依赖中的路由组件接口
1 | class testPage extends React.Component<RouteComponentProps, {}> { |
如果props有其他参数
1 | type Props = RouteComponentProps & { |
导出
使用 withRouter 包装
1 | export default withRouter(testPage); |
如果有引入redux
1 | export default connect(stateToProps, dispatchToProps)(withRouter(testPage)); |
使用
1 | public clickSearch = (value: string) => { |
路由传参
路由表配置
参数地址栏显示,刷新页面,参数不丢失1
<Route path="/test/testpage/:id" component={ OtherDetail } />
需要获取参数的页面的类型声明
1 | // RouteComponentProps里的参数必须为string |
跳转1
this.props.history.push( '/test/testpage/2' );
获取1
this.props.match.params.id
query方法(新版本已废弃)
路由不需要额外配置,参数地址栏不显示,刷新地址栏,参数丢失
跳转1
2
3
4
5
6this.props.history.push({
pathname: '/test/testpage',
query: {
id: '0'
}
})
获取1
this.props.location.query.id
search方法(新版本)
路由不需要额外配置,参数地址栏显示,刷新地址栏,参数不丢失
跳转1
2
3
4
5this.props.history.push({
pathname: '/test/testpage',
search: '?id=1'
})
获取1
this.props.location.search
state方法
路由不需要额外配置,参数地址栏不显示,刷新地址栏,参数丢失
跳转1
2
3
4
5
6this.props.history.push({
pathname: '/test/testpage',
state: {
id: '0'
}
})
获取1
this.props.location.state.id