问题
在用React
开发时 要通过this.props.history.replace('路径')
跳转 ,在this.props
却找不到.history
导致无法跳转 。
原因
由于 React
中,只有在 <Route>
包裹的组件中,才能在 this.props
属性中找到 history
。
解决方案
第一种 : 直接用<Route>
进行包裹。(直接用,不说了)
第二种:不用用React
进行包裹。(以下两种方式)
1、这种方式会出现 Support for the experimental syntax ‘decorators-legacy’ isn’t currently enabled 的报错
import { withRouter } from 'react-router-dom'
@withRouter
class ...
2、是在第一种方式进行修改,解决报错问题;
import { withRouter } from 'react-router-dom'
export default withRouter(组件)
顺便记录下react中页面跳转的方式
this.props.history.replace('路径')
或this.props.history.path('路径')
<Redirect to='路径' />
window.location.href = '路径';
window.open('about:blank').location.href = '路径';
注:不同的方式有不同的使用场景