本文整理汇总了TypeScript中react.useReducer函数的典型用法代码示例。如果您正苦于以下问题:TypeScript useReducer函数的具体用法?TypeScript useReducer怎么用?TypeScript useReducer使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了useReducer函数的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。
示例1: useMapDispatchToCallback
const useKeyBindingsContextState = (): KeyBindingsContextType => {
const [{activeWindowId}, dispatchWindows] = React.useReducer(windowsReducer, windowsInitialState)
const [keyBindingsPerWindow, dispatchKeyBindingsPerWindow] = React.useReducer(
keyBindingsPerWindowReducer,
keyBindingsPerWindowInitialState
)
const addEventListener = useMapDispatchToCallback(
dispatchKeyBindingsPerWindow,
keyBindingsPerWindowCreators.addEventListener
)
const removeEventListener = useMapDispatchToCallback(
dispatchKeyBindingsPerWindow,
keyBindingsPerWindowCreators.removeEventListener
)
const setActiveWindowId = useMapDispatchToCallback(
dispatchWindows,
windowsCreators.setActiveWindowId
)
const unsetActiveWindowId = useMapDispatchToCallback(
dispatchWindows,
windowsCreators.unsetActiveWindowId
)
return React.useMemo(
() => ({
activeWindowId,
keyBindingsPerWindow,
addEventListener,
removeEventListener,
setActiveWindowId,
unsetActiveWindowId
}),
[
activeWindowId,
addEventListener,
keyBindingsPerWindow,
removeEventListener,
setActiveWindowId,
unsetActiveWindowId
]
)
}
开发者ID:foray1010,项目名称:Popup-my-Bookmarks,代码行数:46,代码来源:useKeyBindingsContextState.ts
示例2: createQuery
export default function useRetrieveResource<Model extends BaseModel>(
createQuery: () => AbstractQuery<Model>,
) {
const [state, dispatch] = useReducer<Reducer<Model[]>, () => Promise<void>>(
reducer,
() =>
createQuery().fetch((result: Model[]) => {
(state as any).resolve();
dispatch({ type: 'resolve', result });
}),
initReducer,
);
return state;
}
开发者ID:liwijs,项目名称:liwi,代码行数:15,代码来源:useRetrieveResource.ts
示例3: useMapDispatchToCallback
const useListNavigationContextState = (): ListNavigationContextType => {
const [lists, dispatch] = React.useReducer(listsReducer, listsInitialState)
const removeList = useMapDispatchToCallback(dispatch, listsCreators.removeList)
const resetLists = useMapDispatchToCallback(dispatch, listsCreators.resetLists)
const setHighlightedIndex = useMapDispatchToCallback(dispatch, listsCreators.setHighlightedIndex)
const setItemCount = useMapDispatchToCallback(dispatch, listsCreators.setItemCount)
const unsetHighlightedIndex = useMapDispatchToCallback(
dispatch,
listsCreators.unsetHighlightedIndex
)
return React.useMemo(
() => ({
lists,
removeList,
resetLists,
setHighlightedIndex,
setItemCount,
unsetHighlightedIndex
}),
[lists, removeList, resetLists, setHighlightedIndex, setItemCount, unsetHighlightedIndex]
)
}
开发者ID:foray1010,项目名称:Popup-my-Bookmarks,代码行数:24,代码来源:useListNavigationContextState.ts
示例4: useForceUpdate
export function useForceUpdate() {
return useReducer(forcedReducer, false)[1];
}
开发者ID:LWJGL,项目名称:lwjgl3-www,代码行数:3,代码来源:useForceUpdate.ts
示例5: activeFiltersReducer
const useFilters = () => {
const initialActiveFilters: Filters = {
search: '',
labels: {},
};
function activeFiltersReducer(state: Filters, action: ActiveFiltersAction) {
switch (action.type) {
case ActiveFiltersActionType.SET_SEARCH:
return { ...state, search: action.payload };
case ActiveFiltersActionType.SET_LABEL:
return {
...state,
labels: {
...state.labels,
[action.payload.key]: [
...state.labels[action.payload.key],
action.payload.value,
],
},
};
case ActiveFiltersActionType.REMOVE_LABEL:
return {
...state,
labels: {
...state.labels,
[action.payload.key]: state.labels[action.payload.key].filter(
label => label !== action.payload.value,
),
},
};
case ActiveFiltersActionType.REMOVE_ALL_FILTERS:
return { ...initialActiveFilters, search: state.search };
default:
return state;
}
}
const [activeFilters, dispatchActiveFilters] = useReducer(
activeFiltersReducer,
// @ts-ignore
initialActiveFilters,
);
const setSearchFilter = (search: string) => {
dispatchActiveFilters({
type: ActiveFiltersActionType.SET_SEARCH,
payload: search,
});
};
const setFilterLabel = (key: string, value: string) => {
if (!activeFilters.labels[key]) {
activeFilters.labels[key] = [];
}
if (activeFilters.labels[key].includes(value)) {
removeFilterLabel(key, value);
} else {
dispatchActiveFilters({
type: ActiveFiltersActionType.SET_LABEL,
payload: { key, value },
});
}
};
const removeFilterLabel = (key: string, value: string) => {
dispatchActiveFilters({
type: ActiveFiltersActionType.REMOVE_LABEL,
payload: { key, value },
});
};
const removeAllFiltersLabels = () => {
dispatchActiveFilters({
type: ActiveFiltersActionType.REMOVE_ALL_FILTERS,
payload: { key: '', value: '' },
});
};
const hasActiveLabel = (key: string, value: string): boolean => {
return (
activeFilters.labels[key] && activeFilters.labels[key].includes(value)
);
};
return {
activeFilters,
setSearchFilter,
setFilterLabel,
removeFilterLabel,
removeAllFiltersLabels,
hasActiveLabel,
};
};
开发者ID:marynaKhromova,项目名称:console,代码行数:95,代码来源:Filters.service.ts
示例6: useToggle
export function useToggle(
initialValue: boolean
): [boolean, (force?: boolean) => void] {
return useReducer(reducer, initialValue)
}
开发者ID:8th713,项目名称:cockpit-for-pixiv,代码行数:5,代码来源:useToggle.ts
示例7: useForceUpdate
export function useForceUpdate() {
const [, update] = useReducer(reducer, false)
return update as () => void
}
开发者ID:8th713,项目名称:cockpit-for-pixiv,代码行数:5,代码来源:useForceUpdate.ts
示例8: useMediaControls
export function useMediaControls(player: React.RefObject<HTMLMediaElement>) {
const [state, dispatch] = useReducer(mediaReducer, {
currentTime: 0,
paused: true,
oldVolume: 1,
volume: 1,
muted: false,
});
function pause() {
if (player.current) {
player.current.pause();
}
}
function play() {
if (player.current) {
return player.current.play();
} else {
return Promise.reject();
}
}
function setVolume(volume: number) {
if (player.current) {
if (volume < 0) {
if (state.volume > 0) {
volume = 0;
} else {
return;
}
} else if (volume > 1) {
volume = 1;
if (state.volume < 1) {
volume = 1;
} else {
return;
}
}
player.current.volume = volume;
// no onmuted event, must set on volumechange
if (volume === 0) {
player.current.muted = true;
} else {
player.current.muted = false;
}
dispatch({ type: 'volume', volume });
}
}
function mute() {
setVolume(0);
}
function unmute() {
setVolume(state.oldVolume);
}
function seek(value: number) {
if (player.current) {
player.current.currentTime = value;
}
}
function stop() {
pause();
seek(0);
}
function restart() {
seek(0);
return play();
}
useEffect(() => {
if (player.current !== null) {
dispatch({
type: 'init',
state: {
currentTime: player.current.currentTime,
paused: isPaused(player.current),
oldVolume: player.current.volume,
volume: player.current.volume,
muted: player.current.muted,
},
});
function playPauseHandler(this: HTMLMediaElement) {
dispatch({ type: 'playPause', paused: isPaused(this) });
}
function volumeHandler(this: HTMLMediaElement) {
dispatch({ type: 'volume', volume: this.volume });
}
function seekHandler(this: HTMLMediaElement) {
dispatch({ type: 'seek', currentTime: this.currentTime });
}
player.current.addEventListener('play', playPauseHandler); // fired by play method or autoplay attribute
player.current.addEventListener('playing', playPauseHandler); // fired by resume after being paused due to lack of data
//.........这里部分代码省略.........
开发者ID:LWJGL,项目名称:lwjgl3-www,代码行数:101,代码来源:useMediaControls.ts
示例9: Promise
export default function useRetrieveResourceAndSubscribe<
Model extends BaseModel
>(
createQuery: () => AbstractQuery<Model>,
{ visibleTimeout }: UseResourceAndSubscribeOptions = defaultOptions,
) {
const subscribeResultRef = useRef<SubscribeResult<Model[]> | undefined>(
undefined,
);
const timeoutRef = useRef<ReturnType<typeof setTimeout> | undefined>(
undefined,
);
const resultRef = useRef<Model[] | undefined>(undefined);
const unsubscribe = (): void => {
logger.log('unsubscribe');
// reset timeout to allow resubscribing
timeoutRef.current = undefined;
resultRef.current = undefined;
if (subscribeResultRef.current) {
subscribeResultRef.current.stop();
subscribeResultRef.current = undefined;
}
};
const [state, dispatch] = useReducer<Reducer<Model[]>, () => Promise<void>>(
reducer,
() =>
new Promise((resolve, reject) => {
const query = createQuery();
const queryLogger = logger.context({
resourceName: (query as any).client.resourceName,
key: (query as any).key,
});
queryLogger.debug('init');
const subscribe = (): void => {
queryLogger.debug('subscribing', {
subscribeResultRef: subscribeResultRef.current,
timeoutRef: timeoutRef.current,
});
subscribeResultRef.current = query.fetchAndSubscribe(
(err: Error | null, changes: Changes<Model>) => {
queryLogger.debug('received changes', {
err,
changes,
});
if (err) {
// eslint-disable-next-line no-alert
alert(`Unexpected error: ${err}`);
return;
}
const currentResult = resultRef.current;
const newResult = applyChanges(
currentResult,
changes,
'_id', // TODO get keyPath from client(/store)
);
if (newResult && newResult !== currentResult) {
resultRef.current = newResult;
dispatch({ type: 'resolve', result: newResult });
}
},
);
};
const handleVisibilityChange = () => {
if (!document.hidden) {
if (timeoutRef.current !== undefined) {
queryLogger.debug('timeout cleared');
clearTimeout(timeoutRef.current);
timeoutRef.current = undefined;
} else if (!subscribeResultRef.current) {
queryLogger.info('resubscribe');
subscribe();
}
return;
}
if (subscribeResultRef.current === undefined) return;
queryLogger.debug('timeout visible');
timeoutRef.current = setTimeout(unsubscribe, visibleTimeout);
};
document.addEventListener(
'visibilitychange',
handleVisibilityChange,
false,
);
if (!document.hidden) {
subscribe();
}
}),
initReducer,
//.........这里部分代码省略.........
开发者ID:liwijs,项目名称:liwi,代码行数:101,代码来源:useRetrieveResourceAndSubscribe.ts
注:本文中的react.useReducer函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论