900字范文,内容丰富有趣,生活中的好帮手!
900字范文 > 微信小程序防止重复提交

微信小程序防止重复提交

时间:2021-11-27 15:06:58

相关推荐

微信小程序防止重复提交

问题

微信小程序在真机测试时,遇到这样一种情况:当网络条件差或卡顿的情况下,进行某项操作时,使用者会认为点击无效而进行多次点击,致使多次跳转页面或多次上传同一表单,导致函数或接口被多次调用,实际上使用者只想调用函数和接口一次。

解决方法

添加节流阀,即按下按钮后将方法锁定,等方法执行完再解锁。

wxml:

<input type="text" value="{{msgValue}}" confirm-type="send" bindconfirm="sendMsg" bindinput="bindKeyInput" placeholder="请输入聊天内容" />

JS:

//在页面初始数据data中,声明“锁”: sendMsgStatedata: {sendMsgState: true}//符合消息发送条件的时候,把sendMsgState的值置为false;//并在消息发送成功之后,将消息发送框的value置空的之后,将sendMsgState设为truesend() {let self = this;let msg = self.data.msgValue;if (msg && self.data.sendMsgState) {self.data.sendMsgState = false//加锁app.globalData.nim.sendText({scene: 'URL',to: self.data.doctorId,text: msg,done(error, msg) {if (!error) {//调用成功self.setData({msgValue: ''//保险起见将输入栏一起清空}, () => {self.data.sendMsgState = true//此时按钮解锁})} else {//失败wx.showToast({title: '失败',icon: 'none',duration: 500,mask: true})}}})}}

后续问题

在短时间内快速连按发送按钮仍可能导致多条相同的信息被发送。

猜测:速度太快导致“锁”并没有生效且信息没有被清空。

解决方法

在之前的解决方案,设定flag/js加锁的基础上,增加连续点击按钮事件间隔少于1s时算是同一次事件的规则。

在data中注册lastSendTime,设置值为空;触发发送事件sendMsg的时候,把当前时间保存到变量currentTime;判断当前时间currentTime与上次发送时间的差值是否小于1000;如果是,则发送事件连续触发时间短于1s,停止发送;消息发送成功之后,在置空内容输入框的setData回调方法中,将lastSendTime的值更新为:currentTime。

sendMsg() {let self = this;let msg = self.data.msgValue;// 防止两次点击操作间隔太快let currentTime = new Date();if ((currentTime - this.data.lastSendTime < 1000) || (msg === self.data.msg)) {//发送事件连续触发时间短于1sreturn;}if (msg && self.data.sendMsgState) {self.data.sendMsgState = falseapp.globalData.nim.sendText({url: 'URL',to: self.data.doctorId,text: msg,done(error, msg) {if (!error) {self.setData({msgValue: ''}, () => {self.data.sendMsgState = trueself.data.lastSendTime = currentTime})} else {//消息发送失败wx.showToast({title: '发送失败',icon: 'none',duration: 1500,mask: true})}}})}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。