Files
creator-hub/web/src/shared/hooks/hooks.js
T

34 lines
1.1 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect } from 'react'
export function useTitle(title) {
useEffect(() => { document.title = title }, [title])
}
// 401 之外的业务错误(404/409/503…)直接展示后端 message401 在 dataProvider 里转跳登录页。
export function displayError(error) {
return error?.message || '操作失败'
}
export function conflictError(error, fallback) {
if (error?.status === 409) return `冲突(409):${error.body?.reason || fallback}`
if (error?.status === 503) return `资源未就绪(503):${error.message}`
return displayError(error)
}
export function useUnsavedChanges(dirty) {
useEffect(() => {
if (!dirty) return undefined
const click = (event) => {
const anchor = event.target.closest?.("a[href]")
if (!anchor || !anchor.getAttribute("href")?.startsWith("#/")) return
if (window.confirm("当前内容尚未保存,确定离开吗?")) return
event.preventDefault()
event.stopPropagation()
}
document.addEventListener("click", click, true)
return () => {
document.removeEventListener("click", click, true)
}
}, [dirty])
}