繁体   English   中英

React 有条件地渲染特定路由中的组件

[英]React conditionally render a component in specific routes

这是我的Index.js

ReactDOM.render(
   <React.StrictMode>
        <Provider store={store}>
            <Router>
               <App className="app-main" />
            </Router>
         </Provider>
    </React.StrictMode>,
  document.getElementById('root')
);

这是App.jsx

<Switch>
     appRoutes.map(route =>
          <Route path={route.path} component={route.component} key={route.key}/>
     )}
</Switch>
<BottomNav />

我想在特定路线中呈现BottomNav组件,其中它们也是一些子路线。 我在底部导航中使用了withRouter但它的匹配只是一个“/”,我只能访问位置。 位置对我来说是不够的,因为正如我所说,这些路线中有一些子路线。 因此,例如在个人资料路线中,我有活动和朋友。 我想在个人资料/朋友中呈现BottomNav,但不想在个人资料/活动中呈现我怎样才能做到这一点。 我的解决方案是在 redux 中设置当前路由路径并将其传递给底部导航并检查它是否在我渲染底部导航的有效路由中,但我无法在不同的视图中编写和重复一个函数,直到他们在 redux 中安装更新当前路由。 我忘了说我是 React 的新手,请保持温和并详细解释 tnx :)

我还没有测试过,只是从我的头顶提出来的。 这个想法是你创建一个你的BottomNav应该出现的路线地图。 否则,只需返回 null。

import {withRouter} from 'react-router-dom'

const ROUTES_WITH_BOTTOM_NAV = {
   '/home': true,
   '/profile/friends': true
}

const BottomNav = (props) => {
   const currentPage = props.location.pathname;
   if (!ROUTES_WITH_BOTTOM_NAV[currentPage]) return null;

   return (...yourBottomNavJsx)
}

export const withRouter(BottomNav)

如果这有帮助,请告诉我。

暂无
暂无

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

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