简体   繁体   中英

How to delay the return() of React functional component

I'm using Functional components in my react app. I need to delay the content under the return() of my react component by 3 seconds. Here is the way I'm looking for it. Please help me to do it in this way.

import React, { useEffect, useState } from 'react';

const Example = () => {
    useEffect(() => {

        //some codes

    }, []);

    //some codes

    return (
        <div>
            {/* Return Something */}
        </div>
    );
};

export default Example;
import React, { useEffect, useState } from 'react';

const Example = () => {
    const [loading, setLoading] = useState(true);
    useEffect(() => {

      setTimeout(() => {
         setLoading(false)
      }, 3000)

    }, []);

    //some codes

    if(!loading){
       return <div>loading...</div> 
    }

    return (
        <div>
            {/* Return Something */}
        </div>
    );
};

export default Example;

use the setTimeout method calls a function or runs some code after a period of time, specified using the second argument.

const [state,setState] = useState({
 text:"",
});

useEffect(() => {
const timer = setTimeout(() => {
 setState({
  text:"Hello World"
 });
}, 3000);
return () => clearTimeout(timer);
}, []);

return (
<h1>{state.text}</h1>
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM