简体   繁体   中英

React condtional render (mobile view and Desktop view ) issue

Can anyone please help me? When this code has loaded at the mobile view it has show Desktop view for some milliseconds after that it has show a mobile view. Can anyone correct my code, please? Thanks in advance.

class Header extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
           isLarge:true
        };
        this.updatePredicate = this.updatePredicate.bind(this);
    }

    componentDidMount() {    
        this.updatePredicate();
        window.addEventListener("resize", this.updatePredicate);
    }

    componentWillUnmount() {
        window.removeEventListener("resize", this.updatePredicate);
    }

    updatePredicate() {
         var size = window.innerWidth;
         if(size>767) {
             this.setState({ isLarge:true});
         } else {
             this.setState({ isLarge:false});
         }  
    }

    render() {
        const {isLarge} = this.state;   

        return (
            <div>
                {isLarge ? (<DesktopMenu 
                                categories={categories} 
                                menuOpen={menuOpen} 
                                openMenu={openMenu}/>) 
                         : (<MobileMenu 
                                categories={categories} 
                                menuOpen={menuOpen} 
                                openMenu=openMenu}/>)
                }
            </div>
        );
    }
}

By default your state has isLarge set to true, so even for these millis, it will render the DesktopView.

You could initialize your state with undefined value, not a default one.

    this.state = {
       isLarge: undefined
    };

and then check if value is present

    return (
        <>
        {isLarge === undefined ? "Loading" :
        <div>
            {
             isLarge ?
               <DesktopMenu categories={categories}
                            menuOpen={menuOpen}
                            openMenu={openMenu}
               />
              : 
               <MobileMenu categories={categories}
                           menuOpen={menuOpen}
                           openMenu={openMenu}
               />
            }
        </div>
     }
     </>
    );

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