當前位置: 首頁>>代碼示例>>TypeScript>>正文


TypeScript react.useMemo函數代碼示例

本文整理匯總了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;未經允許,請勿轉載。