问题
This is my 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
<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. I used withRouter in the Bottom nav but its match is just a "/" and i have access to location only. 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. 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. I forgot to say i'm new to React pleas be gentle and explain in details tnx :)
回答1:
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. Else, just return 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.
来源:https://stackoverflow.com/questions/64721310/react-conditionally-render-a-component-in-specific-routes