TypeError:Cannot read property 'goBack' of undefined
或者TypeError:Cannot read property 'push' of undefined
等
原因:在React中,一般组件没有history等方法,因为一般组件没有传值,props收到的是一个空对象,只有路由组件中才有
解决方法:使用withRouter,withRouter
是专门解决一般组件中使用路由组件中的API的情况
- 在一般组件中引入
import {withRouter} from 'react-router-dom'
- 使用
withRouter
暴露组件export default withRouter(Test)
说明:
- withRouter 可以加工一般组件,让一般组件具备路由组件所特有的API
- withRouter的返回值是一个新组件