使用react-router-dom的4.1.1版我有一个用" withRouter"包裹的组件。我已经将路由器添加到上下文中,并且在运行时我在上下文中看到了路由器对象。路线正在按预期进行,页面包含redux形式。但是尝试调用setRouteLeaveHook导致:
未捕获的TypeError:this.context.router.setRouteLeaveHook不是 功能
所以我的问题是:为什么setRouteLeaveHook不能作为函数显示?
在此之前我实际上尝试了几种方法,包括来自mknabe的代码,但它们都会导致相同的错误。
缩写代码:
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Field, reduxForm } from 'redux-form';
import { withRouter } from 'react-router-dom';
...
export class MyDetail extends React.Component {
...
componentDidMount() {
this.context.router.setRouteLeaveHook(this.props.route, () => {
if (true)
return 'You have unsaved information, are you sure you want to leave this page?'
})
}
render() {
...
}
...
MyDetail.propTypes = {
...
route: PropTypes.object,
};
MyDetail.contextTypes = { router: PropTypes.object };
const MyDetailForm = reduxForm({
validate,
form: 'My_detail',
enableReinitialize: true,
})(MyDetail);
const ConnectedMyDetail = connect(mapStateToProps)(MyDetailForm);
export default withRouter(ConnectedMyDetail);