简体   繁体   中英

React-router-dom how to update parent state inside route component

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?

Have you considered adding the Navbar as a component in the Routes, instead of using the state to decide if the navbar should be visible or not?

<Switch>
    <Route exact path='/child' component={ChildPart}/> 
    <Route path="">
         <MyNavBar />
         <Home />
    </Route>
</Switch>

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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