简体   繁体   中英

How to return jsx after setTimeout

I have a loading state that I want to show only if the loading takes more than 1 second (since I don't want to keep showing the loader even if the loading time is just a few milliseconds).

This is the one that shows the loader regardless of the speed of loading:

if(loading) {
    return <div className="loader" />;
}

This is the one with setTimeout:

if(loading) {
    setTimeout(function() {
        return <div className="loader" />;
    }, 1000);
}

I understand that the return statement applies to setTimeout and not the component that's why it doesn't work.

Should I then create a state first (eg isLoadingSlow ) which I will change to true after 1 second in the setTimeout callback? Then based from that state, then I would do a return statement with the loader jsx?

NOTE: this is an answer written based on an answer that was deleted from this post.

I think you need to have two variables, one is loader, another one is show loader. After one second, if it is still loading, we should update the stat to show the loader, otherwise it won't be shown.

 state= { loading: true, showLoader: false } componentDidMount() { setTimeout(() => { if(this.loading){ this.setState({ showLoader: true }) } }, 1000); } render() { if(this.state.showLoader) { return <div className="loader" />; } } 

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