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


TypeScript react.useState函數代碼示例

本文整理匯總了TypeScript中react.useState函數的典型用法代碼示例。如果您正苦於以下問題:TypeScript useState函數的具體用法?TypeScript useState怎麽用?TypeScript useState使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了useState函數的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的TypeScript代碼示例。

示例1: useState

export const useSavedState = (disabled: boolean, saved: boolean) => {
  const [wasUnsaved, setWasUnsaved] = useState(false);
  const [wasSaved, setWasSaved] = useState(false);
  if (!saved && !wasUnsaved) setWasUnsaved(true);
  if (saved && wasUnsaved && !wasSaved) setWasSaved(true);
  return [disabled || saved ? true : !wasUnsaved, saved && wasSaved];
};
開發者ID:este,項目名稱:este,代碼行數:7,代碼來源:useSavedState.ts

示例2: useState

export function useUndo<T>(initialState: T) {
  const [versions, setVersions] = useState<T[]>([initialState]);
  const [currentVersion, setCurrentVersion] = useState(0);

  const hasUndo = currentVersion !== 0;
  const hasRedo = currentVersion !== versions.length - 1;

  const createVersion = (version: T) => {
    const willBranch = currentVersion !== versions.length - 1;

    const nextVersions = willBranch ? versions.slice(0, currentVersion + 1) : versions;

    setVersions([...nextVersions, version]);
    setCurrentVersion(nextVersions.length);
  };

  const undo = () => setCurrentVersion(Math.max(currentVersion - 1, 0));

  const redo = () => setCurrentVersion(Math.min(currentVersion + 1, versions.length - 1));

  return [
    versions[currentVersion],
    createVersion,
    {
      undo,
      redo,
      hasUndo,
      hasRedo,
    },
  ];
}
開發者ID:LWJGL,項目名稱:lwjgl3-www,代碼行數:31,代碼來源:useUndo.ts

示例3: useState

export const useQuery = (value: string): Output => {
  const [result, setResult] = useState<Result>([]);
  const [loading, setLoading] = useState(false);
  const [loaded, setLoaded] = useState(false);
  const debounce = useRef<any>(null);

  useEffect(() => {
    worker.load().then(() => {
      setLoaded(true);
    });
  }, []);

  useEffect(
    () => {
      if (!value) return;

      if (debounce.current) {
        clearTimeout(debounce.current);
      }

      setLoading(true);

      debounce.current = setTimeout(() => {
        worker.solve(value).then((data: any) => {
          setResult(data);
          setLoading(false);
        });
      }, 140);
    },
    [value],
  );

  return { loaded, loading, data: result };
};
開發者ID:kerlends,項目名稱:word-solver,代碼行數:34,代碼來源:useQuery.ts

示例4: useCanvas

export function useCanvas(
    width: number,
    height: number,
    sourceCanvasRef?: RefObject<HTMLCanvasElement>
): [
    HTMLCanvasElement | null,
    CanvasRenderingContext2D | null,
    (ctx: CanvasRenderingContext2D) => void
] {
    const [canvas, setCanvas] = useState<HTMLCanvasElement | null>(null);
    const [ctx, setCtx] = useState<CanvasRenderingContext2D | null>(null);

    useEffect(() => {
        const canvas = sourceCanvasRef
            ? sourceCanvasRef.current!
            : document.createElement('canvas');
        canvas.width = width;
        canvas.height = height;
        const ctx = canvas.getContext('2d')!;
        setCanvas(canvas);
        setCtx(ctx);
    }, []);

    return [canvas, ctx, setCtx];
}
開發者ID:alcarin-org,項目名稱:alcarin,代碼行數:25,代碼來源:CanvasUtils.ts

示例5: useState

function useAsync<Result>(fn: () => Promise<Result>) {
  const [isLoading, setIsLoading] = useState(false);
  const [result, setResult] = useState<Result | null>(null);
  const [err, setError] = useState(null);
  const isMounted = useIsMounted();

  const run = useCallback(async () => {
    setIsLoading(true);

    try {
      const res = await fn();

      if (isMounted.current) {
        setResult(res);
      }
    } catch (error) {
      if (isMounted.current) {
        setError(error);
      }
    } finally {
      if (isMounted.current) {
        setIsLoading(false);
      }
    }
  }, [fn]);

  return {
    isLoading,
    result,
    error: err,
    run,
  };
}
開發者ID:TF2PickupNET,項目名稱:TF2Pickup,代碼行數:33,代碼來源:use-async.ts

示例6: 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,代碼來源:

示例7: useEffect

const useNotifications = () => {
  const [notification, setNotification] = useState<Notification>(
    {} as Notification,
  );
  const [showNotification, setShowNotification] = useState<boolean>(false);
  let timer: number = 0;

  useEffect(() => {
    if (!notification) return;
    if (!Object.keys(notification).length) return;

    setShowNotification(true);
    timer = setTimeout(
      () => setShowNotification(false),
      NOTIFICATION_SHOW_TIME,
    );
    return () => {
      clearTimeout(timer);
    };
  }, [notification]);

  const hideNotification = () => {
    setShowNotification(false);
    clearTimeout(timer);
  };

  const successNotification = (
    title: string,
    content: string | React.ReactNode,
  ) => {
    setNotification({
      title,
      content,
      color: '#359c46',
      icon: 'accept',
    });
  };

  const errorNotification = (
    title: string,
    content: string | React.ReactNode,
  ) => {
    setNotification({
      title,
      content,
      color: '#359c46',
      icon: 'accept',
    });
  };

  return {
    notification,
    showNotification,
    hideNotification,
    successNotification,
    errorNotification,
  };
};
開發者ID:marynaKhromova,項目名稱:console,代碼行數:58,代碼來源:Notifications.service.ts

示例8: useState

export const usePivotPreviewData = (
  indexPattern: IndexPattern,
  query: PivotQuery,
  aggs: PivotAggsConfigDict,
  groupBy: PivotGroupByConfigDict
): UsePivotPreviewDataReturnType => {
  const [errorMessage, setErrorMessage] = useState('');
  const [status, setStatus] = useState(PIVOT_PREVIEW_STATUS.UNUSED);
  const [dataFramePreviewData, setDataFramePreviewData] = useState([]);

  const aggsArr = dictionaryToArray(aggs);
  const groupByArr = dictionaryToArray(groupBy);

  const previewRequest = getDataFramePreviewRequest(indexPattern.title, query, groupByArr, aggsArr);

  const getDataFramePreviewData = async () => {
    if (aggsArr.length === 0 || groupByArr.length === 0) {
      setDataFramePreviewData([]);
      return;
    }

    setErrorMessage('');
    setStatus(PIVOT_PREVIEW_STATUS.LOADING);

    try {
      const resp: any = await ml.dataFrame.getDataFrameTransformsPreview(previewRequest);
      setDataFramePreviewData(resp.preview);
      setStatus(PIVOT_PREVIEW_STATUS.LOADED);
    } catch (e) {
      setErrorMessage(JSON.stringify(e));
      setDataFramePreviewData([]);
      setStatus(PIVOT_PREVIEW_STATUS.ERROR);
    }
  };

  useEffect(
    () => {
      getDataFramePreviewData();
    },
    [
      indexPattern.title,
      aggsArr.map(a => `${a.agg} ${a.field} ${a.aggName}`).join(' '),
      groupByArr
        .map(
          g =>
            `${g.agg} ${g.field} ${g.aggName} ${
              isGroupByDateHistogram(g) ? g.calendar_interval : ''
            } ${isGroupByHistogram(g) ? g.interval : ''}`
        )
        .join(' '),
      JSON.stringify(query),
    ]
  );
  return { errorMessage, status, dataFramePreviewData, previewRequest };
};
開發者ID:elastic,項目名稱:kibana,代碼行數:55,代碼來源:use_pivot_preview_data.ts

示例9: useState

export function useFirstLastSeenDomainQuery<TCache = object>(
  ip: string,
  domainName: string,
  flowTarget: FlowTarget,
  sourceId: string,
  apolloClient: ApolloClient<TCache>
) {
  const [loading, updateLoading] = useState(false);
  const [firstSeen, updateFirstSeen] = useState(null);
  const [lastSeen, updateLastSeen] = useState(null);
  const [errorMessage, updateErrorMessage] = useState(null);

  async function fetchDomainFirstLastSeen() {
    updateLoading(true);
    return apolloClient
      .query<GetDomainFirstLastSeenQuery.Query, GetDomainFirstLastSeenQuery.Variables>({
        query: DomainFirstLastSeenGqlQuery,
        fetchPolicy: 'cache-first',
        variables: {
          sourceId,
          ip,
          domainName,
          flowTarget,
          defaultIndex: chrome.getUiSettingsClient().get(DEFAULT_INDEX_KEY),
        },
      })
      .then(
        result => {
          updateLoading(false);
          updateFirstSeen(get('data.source.DomainFirstLastSeen.firstSeen', result));
          updateLastSeen(get('data.source.DomainFirstLastSeen.lastSeen', result));
          updateErrorMessage(null);
          return result;
        },
        error => {
          updateLoading(false);
          updateErrorMessage(error.message);
          return error;
        }
      );
  }

  useEffect(() => {
    try {
      fetchDomainFirstLastSeen();
    } catch (err) {
      updateFirstSeen(null);
      updateLastSeen(null);
      updateErrorMessage(err.toString());
    }
  }, []);

  return { firstSeen, lastSeen, loading, errorMessage };
}
開發者ID:,項目名稱:,代碼行數:54,代碼來源:


注:本文中的react.useState函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。