fix: 修复缓存一直不及时更新的问题

pull/13/head
moonrailgun 4 years ago
parent e43eb6bdba
commit 8b13dfb913

@ -69,27 +69,58 @@ export function buildCachedRegFn<F extends (...args: any) => any>(
}
// 根据是否为 promise 做区分
const cachedGet: any = isPromise(get)
? async (...args: any) => {
if (isSame(args)) {
return _result;
} else {
const result = await get(...args);
_result = result ?? null;
_lastArgs = args;
return result;
}
}
: (...args: any) => {
if (isSame(args)) {
return _result;
} else {
const result = get(...args);
_result = result ?? null;
_lastArgs = args;
return result;
}
};
const cachedGet: any = (...args: any) => {
if (isSame(args)) {
return _result;
} else {
const result = get(...args);
_result = result ?? null;
_lastArgs = args;
return result;
}
};
const refreshCache = () => {
_result = null;
};
const cachedSet = (fn: F) => {
set(fn);
refreshCache();
};
return [cachedGet, cachedSet, refreshCache];
}
/**
* buildRegFn
* Promise
*/
export function buildCachedRegFnAsync<F extends (...args: any) => any>(
name: string,
defaultFunc?: F
) {
const [get, set] = buildRegFn(name, defaultFunc);
let _result: any = null; // 缓存的返回值
let _lastArgs: any;
function isSame(args: any[]) {
// 当有缓存的返回值且两次参数一致
return _result !== null && _isEqual(args, _lastArgs);
}
// 根据是否为 promise 做区分
const cachedGet: any = async (...args: any) => {
if (isSame(args)) {
return _result;
} else {
const result = await get(...args);
_result = result ?? null;
_lastArgs = args;
return result;
}
};
const refreshCache = () => {
_result = null;

@ -1,4 +1,4 @@
import { buildRegFn, buildCachedRegFn } from './buildRegFn';
import { buildRegFn, buildCachedRegFnAsync } from './buildRegFn';
export const [getErrorHook, setErrorHook] = buildRegFn<(err: any) => boolean>(
'requestErrorHook',
@ -6,4 +6,4 @@ export const [getErrorHook, setErrorHook] = buildRegFn<(err: any) => boolean>(
);
export const [tokenGetter, setTokenGetter] =
buildCachedRegFn<() => Promise<string>>('requestTokenGetter');
buildCachedRegFnAsync<() => Promise<string>>('requestTokenGetter');

@ -7,6 +7,8 @@ import type { FriendRequest } from '../model/friend';
* Redux
*/
export function setupRedux(socket: AppSocket, store: AppStore) {
console.log('初始化Redux上下文...');
// 获取好友列表
socket.request<string[]>('friend.getAllFriends').then((data) => {
store.dispatch(userActions.setFriendList(data));

@ -12,6 +12,7 @@ import {
UserBaseInfo,
} from 'pawchat-shared';
import React, { useCallback, useState } from 'react';
import _isNil from 'lodash/isNil';
const SearchFriendResult: React.FC<{
result: UserBaseInfo | undefined | null;
@ -128,11 +129,7 @@ export const AddFriend: React.FC = React.memo(() => {
</Button>
</div>
{Array.isArray(value) ? (
<SearchFriendResult result={value} />
) : (
<SelfIdentify />
)}
{_isNil(value) ? <SelfIdentify /> : <SearchFriendResult result={value} />}
</div>
);
});

Loading…
Cancel
Save