简体   繁体   中英

How do I remember a React-Router URL parameter when navigating away and then back to a page?

Issue:

I have a React app that uses React-Router-DOM for hash-routing. The app has a main navigation bar with Home and About . The Home content has a sub-nav bar with A , B , and C .

When navigating to www.mysite.com/#/home/ the router defaults (redirects) to www.mysite.com/#/home/A .

When navigating from /#/about to /#/home via the Home nav-link, I want the router to remember which sub-route was last used. Currently, navigating to back to home with the Home nav link, returns to #/home/A


Example:

  1. enter URL www.mysite.com in browser ==> renders /home/#/A
  2. use sub-nav menu under Home to select B ===> renders /#/home/B
  3. use main nav menu to select About ==> renders /#/about
  4. use main nav menu to select Home ==> renders /#/home/B


Structure

<App>
    <header>
        <NavLink to="/home">home</NavLink>
        <NavLink to="/contact">contact</NavLink>
    </header>

    <section>
        <Switch>
            <Redirect exact from="/" to="/home/A" />

            <Route path="/home">
                <div>
                    <sub-header>
                        <NavLink to="/home/A">A</NavLink>
                        <NavLink to="/home/B">B</NavLink>
                        <NavLink to="/home/C">C</NavLink>
                    </sub-header>

                    <div>
                        ... content for home
                        <Switch>
                            <Route path="/home/:id" component={ChildComponentThatUsesID}>
                        </Switch>
                    </div>

                </div>
            </Route>

            <Route path="/about"> ... </Route>              

        </Switch>
    </section>
</App>

Notes

I know that I will need to change the Redirect, that is just there for convenience. I also know that I will have to change the <NavLink to="/home"> to somehow incorporate a variable property or state that will be set when using one of the sub-menu links, but I don't know how to go about doing this.

i've never try this type of things but React Router has the history "component/props". See the documentation here : https://github.com/ReactTraining/history#properties

Use react-router's internal state.

const location = {
  pathname: '/somewhere',
  state: { fromDashboard: true }
}

<Redirect to={location}/>

You can access it later through this.props.location.state .

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