• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

TypeScript react.useMemo函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了TypeScript中react.useMemo函数的典型用法代码示例。如果您正苦于以下问题:TypeScript useMemo函数的具体用法?TypeScript useMemo怎么用?TypeScript useMemo使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了useMemo函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的TypeScript代码示例。

示例1: useHistory

export const useUrlState = <State>({
  defaultState,
  decodeUrlState,
  encodeUrlState,
  urlStateKey,
}: {
  defaultState: State;
  decodeUrlState: (value: RisonValue | undefined) => State | undefined;
  encodeUrlState: (value: State) => RisonValue | undefined;
  urlStateKey: string;
}) => {
  const history = useHistory();

  const urlStateString = useMemo(
    () => {
      if (!history) {
        return;
      }

      return getParamFromQueryString(getQueryStringFromLocation(history.location), urlStateKey);
    },
    [history && history.location, urlStateKey]
  );

  const decodedState = useMemo(() => decodeUrlState(decodeRisonUrlState(urlStateString)), [
    decodeUrlState,
    urlStateString,
  ]);

  const state = useMemo(() => (typeof decodedState !== 'undefined' ? decodedState : defaultState), [
    defaultState,
    decodedState,
  ]);

  const setState = useCallback(
    (newState: State | undefined) => {
      if (!history) {
        return;
      }

      const location = history.location;

      const newLocation = replaceQueryStringInLocation(
        location,
        replaceStateKeyInQueryString(
          urlStateKey,
          typeof newState !== 'undefined' ? encodeUrlState(newState) : undefined
        )(getQueryStringFromLocation(location))
      );

      if (newLocation !== location) {
        history.replace(newLocation);
      }
    },
    [encodeUrlState, history, history && history.location, urlStateKey]
  );

  return [state, setState] as [typeof state, typeof setState];
};
开发者ID:elastic,项目名称:kibana,代码行数:59,代码来源:use_url_state.ts


示例2: useDropTargetMonitor

export function useDropTargetMonitor(): [DropTargetMonitor, TargetConnector] {
	const manager = useDragDropManager()
	const monitor = useMemo(() => new DropTargetMonitorImpl(manager), [manager])
	const connector = useMemo(() => new TargetConnector(manager.getBackend()), [
		manager,
	])
	return [monitor, connector]
}
开发者ID:gaearon,项目名称:react-dnd,代码行数:8,代码来源:drop.ts


示例3: useMemo

export const useKibanaUiSetting = (key: string, defaultValue?: any) => {
  const uiSettingsClient = useMemo(() => getNewPlatform().setup.core.uiSettings, [getNewPlatform]);

  const uiSetting$ = useMemo(() => uiSettingsClient.get$(key, defaultValue), [uiSettingsClient]);
  const uiSetting = useObservable(uiSetting$);

  const setUiSetting = useCallback((value: any) => uiSettingsClient.set(key, value), [
    uiSettingsClient,
  ]);

  return [uiSetting, setUiSetting];
};
开发者ID:elastic,项目名称:kibana,代码行数:12,代码来源:use_kibana_ui_setting.ts


示例4: useTransactionOverviewCharts

export function useTransactionOverviewCharts(urlParams: IUrlParams) {
  const { serviceName, start, end, transactionType } = urlParams;
  const uiFilters = useUiFilters(urlParams);

  const { data, error, status } = useFetcher(
    () => {
      if (serviceName && start && end) {
        return loadTransactionCharts({
          serviceName,
          start,
          end,
          transactionType,
          uiFilters
        });
      }
    },
    [serviceName, start, end, transactionType, uiFilters]
  );

  const memoizedData = useMemo(() => getTransactionCharts(urlParams, data), [
    data
  ]);

  return {
    data: memoizedData,
    status,
    error
  };
}
开发者ID:elastic,项目名称:kibana,代码行数:29,代码来源:useTransactionOverviewCharts.ts


示例5: useTransactionList

export function useTransactionList(urlParams: IUrlParams) {
  const { serviceName, transactionType, start, end } = urlParams;
  const uiFilters = useUiFilters(urlParams);
  const { data = [], error, status } = useFetcher(
    () => {
      if (serviceName && start && end && transactionType) {
        return loadTransactionList({
          serviceName,
          start,
          end,
          transactionType,
          uiFilters
        });
      }
    },
    [serviceName, start, end, transactionType, uiFilters]
  );

  const memoizedData = useMemo(() => getWithRelativeImpact(data), [data]);
  return {
    data: memoizedData,
    status,
    error
  };
}
开发者ID:elastic,项目名称:kibana,代码行数:25,代码来源:useTransactionList.ts


示例6: useTransactionDetailsCharts

export function useTransactionDetailsCharts(urlParams: IUrlParams) {
  const {
    serviceName,
    transactionType,
    start,
    end,
    transactionName,
    kuery
  } = urlParams;

  const { data, error, status } = useFetcher(
    () =>
      loadTransactionDetailsCharts({
        serviceName,
        transactionName,
        transactionType,
        start,
        end,
        kuery
      }),
    [serviceName, transactionName, transactionType, start, end, kuery]
  );

  const memoizedData = useMemo(() => getTransactionCharts(urlParams, data), [
    data
  ]);

  return {
    data: memoizedData,
    status,
    error
  };
}
开发者ID:njd5475,项目名称:kibana,代码行数:33,代码来源:useTransactionDetailsCharts.ts


示例7: useRef

export function useDrop<
	DragObject extends DragObjectWithType,
	DropResult,
	CollectedProps
>(
	spec: DropTargetHookSpec<DragObject, DropResult, CollectedProps>,
): [CollectedProps, ConnectDropTarget] {
	const specRef = useRef(spec)
	invariant(spec.accept != null, 'accept must be defined')

	const [monitor, connector] = useDropTargetMonitor()
	useDropHandler(specRef, monitor, connector)

	const result: CollectedProps = useMonitorOutput(
		monitor,
		specRef.current.collect || (() => ({} as CollectedProps)),
		() => connector.reconnect(),
	)

	const connectDropTarget = useMemo(() => connector.hooks.dropTarget(), [
		connector,
	])

	useEffect(() => {
		connector.dropTargetOptions = spec.options || null
		connector.reconnect()
	}, [spec.options])
	return [result, connectDropTarget]
}
开发者ID:gaearon,项目名称:react-dnd,代码行数:29,代码来源:useDrop.ts


示例8: useApolloClient

export const useSubscription = <T, TVariables = OperationVariables>(
  query: DocumentNode,
  options: SubscriptionOptions<T, TVariables> = {},
): {
  data: T | { [key: string]: void }
  error?: GraphQLError
  loading: boolean
} => {
  const onSubscriptionData = options.onSubscriptionData
  const prevOptions = useRef<typeof options | null>(null)
  const client = useApolloClient()
  const [data, setData] = useState<T | {}>({})
  const [error, setError] = useState<GraphQLError | null>(null)
  const [loading, setLoading] = useState<boolean>(true)

  const subscriptionOptions = {
    query,
    variables: options.variables,
    fetchPolicy: options.fetchPolicy,
  }

  useEffect(
    () => {
      prevOptions.current = subscriptionOptions
      const subscription = client
        .subscribe<{ data: T }, TVariables>(subscriptionOptions)
        .subscribe({
          next: ({ data }) => {
            setData(data)

            if (onSubscriptionData) {
              onSubscriptionData({ client, subscriptionData: data })
            }
          },
          error: err => {
            setError(err)
            setLoading(false)
          },
          complete: () => {
            setLoading(false)
          },
        })

      return () => {
        subscription.unsubscribe()
      }
    },
    [isEqual(prevOptions.current, subscriptionOptions) ? prevOptions.current : subscriptionOptions],
  )

  return useMemo(
    () => ({
      data,
      error,
      loading,
    }),
    [data, error, loading],
  )
}
开发者ID:,项目名称:,代码行数:59,代码来源:


示例9: Component1

/**
 * Hook that allows you to define dynamic (or static) css for use in a component.
 *
 * @param styles The CSS properties to compile
 * @param deps list of dependencies (like in useMemo). *Unlike* useMemo and useEffect,
 * this defaults to [], meaning your styles won't be recalculated at each render
 * (since this is the most common case)
 * @returns a function to compile the style that takes in an optional `prop` parameter
 * (default `className`).
 * 
 * Examples:
 *
 * ```
 // Normal usage
 function Component1() {
   const css = useStyle({ margin: '1rem' })
   return <div {...css()}>My Component</div>
 }
 
 // Pass in props
 function Component2({ type }) {
   const css = useStyle({
     color: type === 'primary' ? 'blue' : 'white'
   }, [type])
   return <button {...css()}>Click Me</button>
 }
 
 // Choose prop name
 function CustomLink() {
   const css = useStyle({ color: 'gray' })
   const activeCss = useStyle({ color: 'black' })
 
   // React Router `Link` component
   return <Link {...css()} {...activeCss('activeClassName')}>Click Me</Link>
 }
 ```
 */
export default function useStyle(styles: CSSProperties, deps: unknown[] = []) {
  return useMemo(() => {
    const rule = StyleSheet.create({ styles });
    return (prop = 'className') => ({
      [prop]: css(rule.styles),
    });
  }, deps);
}
开发者ID:tessenate,项目名称:polyhedra-viewer,代码行数:45,代码来源:useStyle.ts


示例10: useMemo

// Enforce easy types here
function useMakeMapState<MappedState, Args extends ValidArgs>(
  makeMapState: () => (state: State, ...args: Args) => MappedState,
  ...args: Args
): MappedState {
  const mapState = useMemo(makeMapState, []);

  return useMapState(mapState, ...args);
}
开发者ID:TF2PickupNET,项目名称:TF2Pickup,代码行数:9,代码来源:use-store.ts



注:本文中的react.useMemo函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
TypeScript react.useReducer函数代码示例发布时间:2022-05-25
下一篇:
TypeScript react.useLayoutEffect函数代码示例发布时间:2022-05-25
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap