路由守衛(wèi)
const [lock, setLock] = useState(true);
useDidShow(() => {
setLock(true);
});
useEffect(() => {
if (!isWXOrWeb()) {
let unblock;
if (lock) {
unblock = history.block(tx => {
// 只監(jiān)聽(tīng)頁(yè)面回退
if (tx.action === 'POP') {
if (!isEqual(formatValue(ref.current), formatValue(form.getFieldsValue()))) {
// 判斷表單內(nèi)容是否變化奢入,注意要用ref實(shí)時(shí)獲取form表單的值,不然只會(huì)獲 取一次最初的值
Taro.showModal({
title: '確定退出嗎',
content: '退出后未暫存的資料將不會(huì)保存莺匠,請(qǐng)暫存后再退出',
confirmColor: '#00B5DB',
success: function (res) {
if (res.confirm) {
unblock();
setLock(false);
// 異步回退浇衬,不要直接寫回退
setTimeout(() => {
Taro.navigateBack({
delta: 1,
});
}, 50);
} else if (res.cancel) {
}
},
});
} else {
setTimeout(() => {
unblock();
setLock(false);
Taro.navigateBack({
delta: 1,
});
}, 50);
}
} else {
setTimeout(() => {
unblock();
setLock(false);
tx.retry();
}, 50);
}
});
} else {
unblock && unblock();
}
return () => setLock(false);
}
}, [lock]);