English 中文(简体)
其次。 显示装载的概率
原标题:Next.js getServerSideProps show loading
最佳回答

You can use nprogress in your <代码>_app.js

import NProgress from  nprogress ;
import "nprogress/nprogress.css";
import Router from  next/router ;

NProgress.configure({
  minimum: 0.3,
  easing:  ease ,
  speed: 800,
  showSpinner: false,
});

Router.events.on( routeChangeStart , () => NProgress.start());
Router.events.on( routeChangeComplete , () => NProgress.done());
Router.events.on( routeChangeError , () => NProgress.done());

或动态进口到<代码>_app.js,以减少捆绑大小

<编码>Progess Barjs

import Router from  next/router ;
import NProgress from  nprogress ;
import "nprogress/nprogress.css";

NProgress.configure({
    minimum: 0.3,
    easing:  ease ,
    speed: 500,
    showSpinner: false,
});

Router.events.on( routeChangeStart , () => NProgress.start());
Router.events.on( routeChangeComplete , () => NProgress.done());
Router.events.on( routeChangeError , () => NProgress.done());

export default function () {
    return null;
}

<代码>_app.js

import dynamic from  next/dynamic ;
const ProgressBar = dynamic(() => import( components/atoms/ProgressBar ), { ssr: false });

const App = () => {
   ...
   return <>
       ...
       <ProgressBar />
   </>
}

Ps:如果你想要改变进展的颜色,你就可以在全球舞台上战胜一切,就像这样。

#nprogress .bar {
    background: #6170F7 !important;
    height: 3px !important;
}
问题回答

Here is an example using hooks.

<编码>pages/_app.js

    import Router from "next/router";

    export default function App({ Component, pageProps }) {
      const [loading, setLoading] = React.useState(false);
      React.useEffect(() => {
        const start = () => {
          console.log("start");
          setLoading(true);
        };
        const end = () => {
          console.log("finished");
          setLoading(false);
        };
        Router.events.on("routeChangeStart", start);
        Router.events.on("routeChangeComplete", end);
        Router.events.on("routeChangeError", end);
        return () => {
          Router.events.off("routeChangeStart", start);
          Router.events.off("routeChangeComplete", end);
          Router.events.off("routeChangeError", end);
        };
      }, []);
      return (
        <>
          {loading ? (
            <h1>Loading...</h1>
          ) : (
            <Component {...pageProps} />
          )}
        </>
      );
    }

你们可以形成一种习俗:

<编码>使用PageLoading.ts

import Router from  next/router ;
import { useEffect, useState } from  react ;

export const usePageLoading = () => {
  const [isPageLoading, setIsPageLoading] = useState(false);

  useEffect(() => {
    const routeEventStart = () => {
      setIsPageLoading(true);
    };
    const routeEventEnd = () => {
      setIsPageLoading(false);
    };

    Router.events.on( routeChangeStart , routeEventStart);
    Router.events.on( routeChangeComplete , routeEventEnd);
    Router.events.on( routeChangeError , routeEventEnd);
    return () => {
      Router.events.off( routeChangeStart , routeEventStart);
      Router.events.off( routeChangeComplete , routeEventEnd);
      Router.events.off( routeChangeError , routeEventEnd);
    };
  }, []);

  return { isPageLoading };
};

and then inside your App component use it: _app.js

import Router from "next/router";
import { usePageLoading } from  ./usePageLoading ;

export default function App({ Component, pageProps }) {
  const { isPageLoading } = usePageLoading();

  return (
    <>
      {isPageLoading ? (
        <h1>Loading...</h1>
      ) : (
        <Component {...pageProps} />
      )}
    </>
   );
}

仅加上先前的答复,您可在处理器中收到<代码>url参数,并将之用于过滤,您希望通过这些途径<>。 a 装载状态,未加装。 简单例子见<代码>_app.js:

function MyApp({ Component, pageProps: { ...pageProps } }: AppProps) {
    const router = useRouter();

    const [isLoading, setIsLoading] = React.useState(false);

    React.useEffect(() => {
        const handleChangeStart = (url: string) => {
            if (url === "<root_to_show_loading>") {
                setIsLoading(true);
            }
        };

        const handleChangeEnd = (url: string) => {
            if (url === "<root_to_show_loading") {
                setIsLoading(false);
            }
        };

        router.events.on("routeChangeStart", handleChangeStart);
        router.events.on("routeChangeComplete", handleChangeEnd);
        router.events.on("routeChangeError", handleChangeEnd);
    }, []);

    return (
        <main>
            {isLoading ? <LoadingSpinner /> : <Component {...pageProps} />}
        </main>
    );

}

export default MyApp;

如何简单地增加一个部件级的装货站(五)在每条线路变动中增加一个装载机,因为某些路线的变化可能不需要服务器的附带提供)。

在相关问答时间发生变化时,当有关问询时间发生变化时,当有关职位被id时,将国家定为假日,在这种情况下,员额数据得到更新。

据此:

pages/post/index.js:

import React from "react";
import Layout from "../../components/Layout";
import { useRouter } from  next/router ;

function Post({ post }) {
  const router = useRouter();
  const [isLoading, setIsLoading] = useState(false);
  
  // loading new post
  useEffect(()=> {
   setIsLoading(true);
  }, [router.query?.id]);
  
  // new post loaded
  useEffect(()=> {
   setIsLoading(false)
  }, [post]);

  return (
    <>
    {isLoading ? (
      <h1>Loading...</h1>
     ) : (
      <Layout title={post.name}>
       <pre>{JSON.stringify(post, undefined, 2)}</pre>
      </Layout>
    )}
    </> 
  );
}

export async function getServerSideProps({ query }) {
  return fetch(
    `${process.env.API_URL}/api/post?id=${query.id}`
  )
    .then(result => result.json())
    .then(post => ({ props: { post } }));
}

export default Post;

在90条法典行(vs NProgress v.0.20)中,进步节有470条线,js + 70条线。

import { useEffect, useReducer, useRef } from  react ;

import { assert } from  ./assert ;
import { wait } from  ./wait ;
import { getRandomInt } from  ./getRandomNumber ;

let waitController: AbortController | undefined;

// https://gist.github.com/tkrotoff/db8a8106cc93ae797ea968d78ea28047
export function useProgressBar({
  trickleMaxWidth = 94,
  trickleIncrementMin = 1,
  trickleIncrementMax = 5,
  dropMinSpeed = 50,
  dropMaxSpeed = 150,
  transitionSpeed = 600
} = {}) {
  // https://stackoverflow.com/a/66436476
  const [, forceUpdate] = useReducer(x => x + 1, 0);

  // https://github.com/facebook/react/issues/14010#issuecomment-433788147
  const widthRef = useRef(0);

  function setWidth(value: number) {
    widthRef.current = value;
    forceUpdate();
  }

  async function trickle() {
    if (widthRef.current < trickleMaxWidth) {
      const inc =
        widthRef.current +
        getRandomInt(trickleIncrementMin, trickleIncrementMax); // ~3
      setWidth(inc);
      try {
        await wait(getRandomInt(dropMinSpeed, dropMaxSpeed) /* ~100 ms */, {
          signal: waitController!.signal
        });
        await trickle();
      } catch {
        // Current loop aborted: a new route has been started
      }
    }
  }

  async function start() {
    // Abort current loops if any: a new route has been started
    waitController?.abort();
    waitController = new AbortController();

    // Force the show the JSX
    setWidth(1);
    await wait(0);

    await trickle();
  }

  async function complete() {
    assert(
      waitController !== undefined,
       Make sure start() is called before calling complete() 
    );
    setWidth(100);
    try {
      await wait(transitionSpeed, { signal: waitController.signal });
      setWidth(0);
    } catch {
      // Current loop aborted: a new route has been started
    }
  }

  function reset() {
    // Abort current loops if any
    waitController?.abort();
    setWidth(0);
  }

  useEffect(() => {
    return () => {
      // Abort current loops if any
      waitController?.abort();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return {
    start,
    complete,
    reset,
    width: widthRef.current
  };
}
import { useRouter } from  next/router ;
import { useEffect } from  react ;

import { useProgressBar } from  ./useProgressBar ;

const transitionSpeed = 600;

// https://gist.github.com/tkrotoff/db8a8106cc93ae797ea968d78ea28047
export function RouterProgressBar(
  props?: Parameters<typeof useProgressBar>[0]
) {
  const { events } = useRouter();

  const { width, start, complete, reset } = useProgressBar({
    transitionSpeed,
    ...props
  });

  useEffect(() => {
    events.on( routeChangeStart , start);
    events.on( routeChangeComplete , complete);
    events.on( routeChangeError , reset); // Typical case: "Route Cancelled"

    return () => {
      events.off( routeChangeStart , start);
      events.off( routeChangeComplete , complete);
      events.off( routeChangeError , reset);
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return width > 0 ? (
    // Use Bootstrap, Material UI, Tailwind CSS... to style the progress bar
    <div
      className="progress fixed-top bg-transparent rounded-0"
      style={{
        height: 3, // GitHub turbo-progress-bar height is 3px
        zIndex: 1091 // $zindex-toast + 1 => always visible
      }}
    >
      <div
        className="progress-bar"
        style={{
          width: `${width}%`,
          //transition:  none ,
          transition: `width ${width > 1 ? transitionSpeed : 0}ms ease`
        }}
      />
    </div>
  ) : null;
}

如何使用:

// pages/_app.tsx

import { AppProps } from  next/app ;
import Head from  next/head ;

import { RouterProgressBar } from  ./RouterProgressBar ;

export default function App({ Component, pageProps }: AppProps) {
  return (
    <>
      <Head>
        <title>My title</title>
        <meta name="description" content="My description" />
      </Head>

      <RouterProgressBar />

      <Component {...pageProps} />
    </>
  );
}

更具体地说,https://gist.github.com/tkrotoff/db8a8106cc93a797ea968d78ea 28047

为补充先前的答复并显示完整的编码,您可加上“密码><>>>>>> 截止日期/代码>的延迟。 在该事件中确定状态时,避开在快速装货路线上(或者固定航线或随时可以走的服务器线路)装货的浮标。

import Router from  next/router ;
import { useEffect, useRef, useState } from  react ;

const usePageLoad = (delay = 200) => {
  const timeoutRef = useRef();
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const start = () => {
      timeoutRef.current = window.setTimeout(() => {
        setLoading(true);
      }, delay);
    };
    const end = () => {
      window.clearTimeout(timeoutRef.current);
      setLoading(false);
    };
    Router.events.on( routeChangeStart , start);
    Router.events.on( routeChangeComplete , end);
    Router.events.on( routeChangeError , end);
    return () => {
      Router.events.off( routeChangeStart , start);
      Router.events.off( routeChangeComplete , end);
      Router.events.off( routeChangeError , end);
    };
  }, [delay]);

  return loading;
};

export default usePageLoad;

然后,在<代码>-应用上使用这个标题,并视需要调整延迟适用。

import PageLoader from  ../components/PageLoader ;
import usePageLoad from  ../components/use-page-load ;

const App = ({ Component, pageProps }) => {
  const loading = usePageLoad();

  return (
    {
       loading
          ? <PageLoader />
          : <Component {...pageProps} />
    }
  );
};

我使用了“@marko424”的习俗 h。

但是,我只需要在某些网页上显示装货量,而不用“Loading. ......”每个页数的ms。

因此,我创造了一个超支的背景,并总结了以下部分:

<OverlayProvider>
    <Component {...pageProps} />
</OverlayProvider>

Inside OverlayProvider:

function OverlayProvider({ children }: OverlayProps) {
    const { isPageLoading } = usePageLoading();
    const overlayData = {
        isPageLoading,
    };
    return (
        <OverlayContext.Provider value={overlayData}>{children}</OverlayContext.Provider>
    );
}
export { OverlayProvider };
export default OverlayContext;

现在,从我需要超负荷的网页上,我可以使用:

const { isPageLoading } = useContext(OverlayContext);

然后,有条件地提交联合材料。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.