简体   繁体   English

使用 React Router 防止组件安装在每个渲染上

[英]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,我想防止每个组件都安装在每次渲染上,我正在使用 React Router,

I changed loading them with component={ComponentName} to render{() => < ComponentName />} with no success.我将使用component={ComponentName}加载它们更改为render{() => < ComponentName />}没有成功。

It seems that this is the natural behavior, but I guess there mus be a way to change it似乎这是自然行为,但我想一定有办法改变它

Here is my App.js这是我的 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 .使用react-router-dom中的Switch组件。 The documentation says:文档说:

How is this different than just using a bunch of Route s?这与仅使用一堆Route有什么不同? Switch is unique in that it renders a route exclusively. Switch的独特之处在于它专门呈现一条路线。 In contrast, every Route that matches the location renders inclusively.相比之下,与位置匹配的每个Route都会以包容性方式呈现。

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>
    );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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