I have a class parent class App containing a navbar and a bunch of routes:
function App() {
const [showNavbar, setShowNavbar] = useState(true);
return (
<>
<MyNavBar show={showNavbar}/>
<Switch>
<Route exact path='/child' component={() => <ChildPart setter={showNavbar}/>}/>
<Route> ... //other routes
</Switch>
</>
)
}
function ChildPart(props) {
const [data, setData] = useState("");
// hide navbar
useEffect(() => {
console.log("child init"); // this got printed twice
props.setter(false);
}, [props.setter]);
// get data at first mount;
useEffect(()=>{
setData(api.loadUserInfo());
}, []);
return (<div>
Data here: {data}
</div>)
}
What I want to achieve is to have navbar change based on which page a user is currently at. For example, hide navbar when use is visiting /child
But by implementing it this way, the ChildPart seems got mount and unmount for twice since the parent is rendered and rotues are also a part of the App.
This causes unnecessary API calls inside the child component.
Is there any way to address this?
If hiding one (MyNavBar) component by navigating to one (or more) urls is a goal, something like this could work. Unfortunatelly negative lookup (regex) is not supported by react router so we can't use something like this (?!child)
.
Another thing which you can do is making MyNavBar
aware of current url by wrapping it withRouter
HOC or using useLocation
hook. Than, you can do your logic in MyNavBar
depending on url.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加