不务正业的iOS 开发者,大前端的发展方向中会遇到很多问题,故有此文章。
环境
Taro+React+TS
一、时间的比较异常
从前端的文档中,后端返回的格式化字符串能直接比较大小,但是在iOS 的小程序版本却异常。2023-05-25 18:02: 55
与 2023-05-24 18:02: 55
却不能正常比较。需要手动将格式化字符串的 -
替换成/
就能正常输出时间大小了。
强哥祖传代码镇楼
/**
* @description 格式化时间
* @param value 时间
* @param pattern 格式化的模式
*/
export function formatDate(value: number | string, pattern = 'YYYY-MM-DD hh:mm:ss') {
if (!value) {
return ''
}
let val: any = value
if (typeof val === 'string') {
val = val.replace(/-/g, '/')
}
if (/^\d{4}\/\d{1,2}$/.test(val)) {
val += '/01'
}
const date = new Date(val)
const chinese = ['一', '二', '三', '四', '五', '六', '日']
let model = pattern
const year = String(date.getFullYear())
const month = String(date.getMonth() + 1)
const week = String(date.getDay())
const day = String(date.getDate())
const hour = String(date.getHours())
const minute = String(date.getMinutes())
const second = String(date.getSeconds())
const time = String(date.getTime())
if (model === 'time' || model === 'Time') {
return time
}
model = model.replace(/YYYY/, year)
model = model.replace(/YY/, String(year).slice(2))
model = model.replace(/MM/, addZero(month))
model = model.replace(/M/, month)
model = model.replace(/[wW]+/, '星期' + chinese[week])
model = model.replace(/DD/, addZero(day))
model = model.replace(/D/, day)
model = model.replace(/hh/, addZero(hour))
model = model.replace(/h/, hour)
model = model.replace(/mm/, addZero(minute))
model = model.replace(/m/, minute)
model = model.replace(/ss/, addZero(second))
model = model.replace(/s/, second)
return model
}
二、Taro.nextTick(callback)
延迟一部分操作到下一个时间片再执行。(类似于 setTimeout)
小程序中我们可能使用到下一个时间碎片中执行,但是使用nextTick
可能会出现问题,比如说:页面未渲染完成nextTick 就执行了,这又是为什么呢?问题代码业务快。
useEffect(() => {
Taro.nextTick(() => {
createSelectorQuery()
.selectAll(`#noticeWrap,#wrap`)
.boundingClientRect((rect) => {
if (rect[0].width < rect[1].width) {
const duration = Math.floor(divide(rect[1].width, divide(speed, 1000)))
setDuration(duration)
setTransStatus(ETransState.Init)
}
})
.exec()
})
}, [list])
解决方案
强哥方案:使用 setTimeout
来代替 setTimeout(() => {} , 200)
说明
小程序使用的是Hybrid
技术,使用的是双线程技术,即js 代码
和 渲染
是分开的。故天生延时,使用Taro.nextTick 中执行了网络请求后的列表,去查询Dom 节点,即页面已经就渲染出来的。故使用来个200ms 延时供dom
操作。强哥祖传传送门
三、自动获取用户昵称
当然微信关于这些权限是一直在改,只需要声明一下 type="nickname"就行了,但是自动获取到的
nickName
并没有走onIput
事件
解决方案
这次是我李总给的方案,不是强哥了。
<Input
id="nickname"
className="cell-input"
type="nickname"
value={user.nickName}
placeholder="请填写,最多20字"
onInput={(e) => onTextFieldInput(e, 'nickName')}
maxlength={20}
placeholderStyle={process.env.TARO_ENV === 'weapp' ? 'color: #d1d1d6;font-size: 28rpx;' : 'color: #d1d1d6;font-size: 28;'}
/>
const onFormSubmit = () => {
Taro.createSelectorQuery()
.select('#nickname')
.fields({
properties: ['value']
})
.exec(async (res) => {
const nickName = res[0].value
let tmpUser = { ...user, nickName }
await updateMemberInfo(tmpUser)
navigateBack()
// 处理nickname
})
}
logs
- 2023.05.27 update Tips3.