react+dva 用户离开,路由拦截,提示用户暂未保存 - Go语言中文社区

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表示可以直接跳转,无需验证
版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_42833001/article/details/90046134
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2021-05-30 12:41:54
  • 阅读 ( 566 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

推荐文章

猜你喜欢