[英]React conditionally render a component in specific routes
This is my Index.js这是我的Index.js
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<Router>
<App className="app-main" />
</Router>
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
And here is App.jsx这是App.jsx
<Switch>
appRoutes.map(route =>
<Route path={route.path} component={route.component} key={route.key}/>
)}
</Switch>
<BottomNav />
I want to render the BottomNav component in specific routes in which they are some sub routes too.我想在特定路线中呈现BottomNav组件,其中它们也是一些子路线。 I used withRouter in the Bottom nav but its match is just a "/" and i have access to location only.
我在底部导航中使用了withRouter但它的匹配只是一个“/”,我只能访问位置。 Location is not enough for me because as i said there are some sub routes in those routes.
位置对我来说是不够的,因为正如我所说,这些路线中有一些子路线。 So for example in a profile route i have activities and friends.
因此,例如在个人资料路线中,我有活动和朋友。 i want render BottomNav in profile/friends but not in profile/activities how can i achieve this.
我想在个人资料/朋友中呈现BottomNav,但不想在个人资料/活动中呈现我怎样才能做到这一点。 My solution was to set current route path in redux and pass it to bottom nav and check if it's in valid routes i render bottom nav but i cant write and repeat a function hundered time in different views to when they mounted update current route in redux.
我的解决方案是在 redux 中设置当前路由路径并将其传递给底部导航并检查它是否在我渲染底部导航的有效路由中,但我无法在不同的视图中编写和重复一个函数,直到他们在 redux 中安装更新当前路由。 I forgot to say i'm new to React pleas be gentle and explain in details tnx :)
我忘了说我是 React 的新手,请保持温和并详细解释 tnx :)
I haven't tested it, just brought it up from the top of my head.我还没有测试过,只是从我的头顶提出来的。 The idea is that you create a map of routes where your BottomNav should appear.
这个想法是你创建一个你的BottomNav应该出现的路线地图。 Else, just return null.
否则,只需返回 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)
Let me know if that helped.如果这有帮助,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.