路由拦截

需求 当前页面数据修改后未保存时,对路由跳转进行拦截

参考

原理 Prompt的message属性除了字符串还可以传递一个函数 这个函数 return true 的时候路由可以正常切换, return false 时候路由切换就被拦截

import React, {Component} from 'react';
import {Prompt} from 'react-router';
 
class Demo extends Component {
    	state = {
			isPrompt: false, // true 数据未编辑
		};
    	handlePrompt = location => {
		/**
		 * return true 路由正常
		 * return false 路由切换被拦截
		 * */
		const {history} = this.props;
		if (!this.state.isPrompt) {
            // 数据编辑过了 离开页面时候要判断是不是要保存
      this.isUpdate = false; // 进入编辑提示框后将数据更新关闭,不然点击关闭后还会循环打开提示框
      const data = {
				title: '提示',
				content: '您还未保存页面内容,确定需要离开吗?',
				okText: '保存离开',
				cancelText: '不保存离开'
			};
			ConfirmModal(
				data,
				close => {
					this.setState({isPrompt: true}, () => {
						console.log(1);
						history.push({pathname: location.pathname, state: location.state});
						close();
					});
				},
				close => {
					this.setState({isPrompt: true}, () => {
						console.log(2);
						history.push({pathname: location.pathname, state: location.state});
						close();
					});
				}
			);
			return false;
		}
		return true;
	};
    
	render() {
		return(
         <div>
        	<Prompt message={this.handlePrompt} />
        </div>;
        ) 
	}
 
	isUpdate = true; //用于判断是否执行数据更新
	componentDidUpdate() {
		if (this.isUpdate) {
			const res = _.isEqual(this.state.parameter, this.state.sourceData);
			this.state.isPrompt = res;
		}
	}
}
 
export default a;