umi#useParams TypeScript Examples

The following examples show how to use umi#useParams. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: _layout.tsx    From bext with MIT License 4 votes vote down vote up
MetaLayout: FC = ({ children }) => {
  const params = useParams<{ id: string }>();
  const { getPreviewMeta } = usePreview();
  const { prefix } = useMeta();

  const [versions, setVersions] = useState<MetaVersion[]>();
  const [currentMeta, setCurrentMeta] = useState<Meta>();
  const [currentVersion, setCurrentVersion] = useState<string>();

  const { loading: allLoading, error: indexError } = useRequest(
    async () => {
      if (params.id === 'preview') {
        setCurrentMeta(await getPreviewMeta());
      } else {
        const response = await fetch(`${prefix}/${params.id}/_index.json`);
        const metaIndex: MetaIndex = await response.json();

        setVersions(metaIndex.versions);
        setCurrentMeta(
          Object.assign({}, metaIndex.meta, { id: String(params.id) }),
        );
        setCurrentVersion(metaIndex.versions[0].hash);
      }
    },
    {
      refreshDeps: [params.id, getPreviewMeta],
    },
  );

  const {
    loading: metaLoading,
    run: setVersion,
    error: metaError,
  } = useRequest(
    async (hash: string) => {
      setCurrentVersion(hash);
      const response = await fetch(`${prefix}/${params.id}/${hash}.json`);
      setCurrentMeta({ ...(await response.json()), id: String(params.id) });
    },
    { manual: true, refreshDeps: [params.id] },
  );

  const { notify } = useNotifications();

  useEventListener('message', ({ data }) => {
    if (
      data?.type === 'bext/unknown-install' &&
      typeof data?.payload?.build === 'string'
    ) {
      copy(data.payload.build);
      notify({
        message: '当前浏览器不支持安装,已将脚本内容复制到剪切板',
        status: 'info',
      });
    }
  });

  if (allLoading) {
    return <Spinner size={SpinnerSize.large} className="w-full h-full" />;
  }

  if (indexError || metaError) {
    return (
      <div className="w-full h-full flex flex-col items-center justify-center">
        出错了...
      </div>
    );
  }

  return (
    <MetaDetailContext.Provider
      value={{
        versions,
        currentVersion,
        setVersion,
        currentMeta,
        allLoading,
        metaLoading,
        isPreview: params.id === 'preview',
      }}
    >
      {children}
    </MetaDetailContext.Provider>
  );
}