简体   繁体   中英

Preventing components to mount on each render with React Router

I want to prevent each component to get mounted on each rendering, I'm using React Router,

I changed loading them with component={ComponentName} to render{() => < ComponentName />} with no success.

It seems that this is the natural behavior, but I guess there mus be a way to change it

Here is my App.js

export default function App() {
    return ( 
        <div className = "App" >
            <Provider store={store}>
                <Route path="/" render={() => <Header />} />  
                <Route exact path="/" render={() => <ShowSplashWindow />} />  
                <Route path="/countries" render={() => <Countries />} />  
                <Route path="/createactivity" render={() => <CreateActivity />} />  
            </Provider>
        </div>
    );
}

And here are my routes paths:

                <nav className={style.nav}>
                    <Link to="/" className={style.subNav}>
                        <p>Init</p>
                    </Link>
                    <Link to="/countries" className={style.subNav}>
                        <p>Countries</p>
                    </Link>
                    <Link to="/createactivity" className={style.subNav}>
                        <p>Create Activities</p>
                    </Link>
                </nav>

I've searched the internet, it says that the render approach resolves the issue, but in my case it doesn't

Rafael

Use Switch component from react-router-dom . The documentation says:

How is this different than just using a bunch of Route s? Switch is unique in that it renders a route exclusively. In contrast, every Route that matches the location renders inclusively.

export default function App() {
    return ( 
        <div className = "App" >
            <Provider store={store}>
                <Route path="/" render={() => <Header />} />  
                <Switch>
                  <Route exact path="/" render={() => <ShowSplashWindow />} />  
                  <Route path="/countries" render={() => <Countries />} />  
                  <Route path="/createactivity" render={() => <CreateActivity />} />  
                </Switch>
            </Provider>
        </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