简体   繁体   中英

Accessing data passed from NavLink after redirecting from home page to a specific page using react router

I am working on a react web app and i am using react router. I want to pass data from the NavLink to my Movies component. The NavLink is shown below.


<ul>
   <li id="movies">
       <NavLink exact to = {{pathname: "/", state:{page: 1}}}  > Movies </NavLink>
   </li>
</ul>

In my router, i want to redirect to movies/all/1 from the landing page. My routes are:


 <Route exact path="/" render={() => <Redirect to="/movies/all/1" />} />
 <Route exact path = "/movies/:genre/:genrePage" component = {Movies} />

In the Movies component, i can access the route parameters but i am failing to access the data, {page: 1} , passed from NavLink via location props. I keep getting undefined as the value of props.location.state . How do i go about this? I don't want the data i am passing to be in the url .

EDIT

Perhaps to clarify. The question below partly answers my question.

However i am still failing to access the data passed from Link when the page is first loaded and then redirected from root path / to /movies/all/1 . It is only accessible after Link has been clicked.

Redirect component doesn't pass location.state to the next route (ie /movies/all/1 ).

If you want to do that, you need to get location.state from your Route / and pass it down to Redirect .

It would look something like that:

<Route exact path="/" render={({ location }) => <Redirect to={{ pathname: "/movies/all/1", state: 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