react+dva 用戶離開,路由攔截,提示用戶暫未保存

需求,當用戶將要在當前頁面離開的時候(本次的實現,離開包括前進,後退與路由的切換),如果用戶未進行保存的操作,則進行自定義的彈窗提示用戶。(本次用的是antd的組件進行自定義的彈窗的搭建)
在這裏插入圖片描述
實現簡直曲折,找了很多的方法,但是發現大多數的都是基於react-router或者react-router-dom,因爲本次的項目是基於dva,進行架構,頁面路由的跳轉,也是基於dva中封裝的路由,終於,黃天不負有心人,最後查到了方法,在此版本的實踐,確實是靠譜的法子。

//當前項目的版本相關
    "react": "^16.2.0",
    "dva": "^2.4.1",

重要代碼,Prompt的引入,因爲dva的路由是基於react-router 4.0的版本上進行的封裝,所以這裏的引入可以直接從dva的路由中進行引入

import {routerRedux,Prompt} from 'dva/router';

在與state的同級目錄下設置一個屬性,作爲一個flag進行使用(如果設置isSave的值爲true,那麼不會進行離開彈窗的提示)

isSave:false

重要的函數代碼

  // 處理自定義離開彈窗
  handlePrompt =(location )=>{
    // 如果當前的保存爲false,則彈窗提醒用戶進行保存操作
    if (!this.isSave) {
      this.showModalSave(location);
      return false;
    }
    return true;
  }
  // 展示離開的提示的彈窗
  showModalSave = location => {
    this.setState({
      modalVisible: true,
      location,
    });
  }
  // 取消是的路由跳轉
  gotoNewUrl(url){
    const {dispatch,history } = this.props
    dispatch(routerRedux.push({
      pathname:url,
    }));
  }
  // 點擊取消關閉彈窗
  closeModalSave=()=>{
    const { location } = this.state;
    const {dispatch,history } = this.props
    this.isSave = true;
    this.setState({
      modalVisible: false,
    },()=>{
      this.gotoNewUrl(location.pathname)
    });
  }
  // 點擊確認,進行頁面保存操作,和保存成功後路由的跳轉
  handleSaveAuto = () => {
    const { location } = this.state;
    const { history } = this.props;
    this.isSave = true;
    this.setState({
      modalVisible: false,
    });
    //進行保存操作的處理,這裏可以換成自己點擊確認後需要做的操作
    this.handleSavePaper('save','exit',location.pathname)
  }

html結構,

 <Prompt message={this.handlePrompt}/>
 <Modal 
     title="溫馨提示"
     visible={this.state.modalVisible}
     closable={false}
     centered
     onCancel={this.closeModalSave}
     footer={null}
 >
   <p>即將離開當前頁面,是否保存當前修改?</p>
   <div style={{textAlign:'right'}}>
     <Button type='primary' onClick={this.handleSaveAuto}>保存</Button>
     <Button style={{marginLeft:'20px'}} onClick={this.closeModalSave}>取消</Button>
   </div>
 </Modal>

關於Prompt 組件,prompt組件的message屬性,可以直接傳入字符串,也可以傳入一個方法

message
    傳遞字符串,用於提示用戶的展示信息
    傳遞函數,可以接受location對象作爲參數
        <prompt message={location => {
            console.log(location);
            return true
        }}
        return true表示可以直接跳轉,無需驗證
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章