設(shè)計思路
為共享數(shù)據(jù)生成setData()
與useData()
對袄秩。
-
setData()
: 初始化或更新共享數(shù)據(jù) -
useData()
:為react hook,用于獲取最新的共享數(shù)據(jù)
代碼
import { useCallback, useEffect, useState } from 'react'
export default function factory(
service, initialValue
) {
let store, fetchPromise, reactions = []
const useData = () => {
const [current, setCurrent] = useState(store ?? initialValue)
const reaction = useCallback(() => setCurrent(store ?? initialValue), [])
useEffect(() => {
const run = async () => {
const currentFetchPromise = (fetchPromise = fetchPromise ?? service())
setCurrent(store = await currentFetchPromise)
fetchPromise = null
}
reactions.push(reaction)
if (!cache) run()
// hook destroy時辩涝,移除reaction
return () => reactions = reactions.filter(f => reaction !== f)
}, [])
return current
}
const setData = (data) => {
store = data
reactions.forEach(fn => fn()) // Call reactions
}
return { useData, setData }
}
使用例子:
// 創(chuàng)建數(shù)據(jù)共享鉤子
export const {useData as useUserData, setData as setUserData } = factory(() => {
return Promise.resolve({ id: 123456, username: '請叫我Pro大叔' })
})
// Login Component
const Login = () => {
// 取值
const login = () => {
// after login
setUserData(userData);
}
....
}
// User Component
const User1 = () => {
// 取值
const user = useUserData()
....
}