How to pass props to <Link> in React Router? React.js, javascript

蹲街弑〆低调 提交于 2020-12-07 06:44:06

问题


I have this code here. On click of button, the lat and lon gets passed to a method called getFood which expects the params of lat and lon to make the right API call based on the location.

     <button
            onClick={() => this.props.onClick(meetup.venue.lat, meetup.venue.lon)}>
            <Link to="/restaurants">Find Restaurants</Link>
     </button>

How can I pass this.props.onClick(meetup.venue.lat, meetup.venue.lon) into my <Link to="/restaurants">Find Restaurants</Link> ?

The user would have to click on the button, and THEN the link to 1) make the api call based on the location and then 2) to render the new component. Of course this is bad UX so I would like to not have the button element all together, if possible.

On my restaurants component, I can make the API call on componentDidMount however, I would still need the location.

Any suggestions?


回答1:


In Link you can pass your data in state key and retrive it in a component which will load on /forgot-password route.

<Link 
    className="link-text-color"
    to={{
         pathname: "/forgot-password",
         state: { modal: true, returnTo:this.props.location.pathname}
       }}
>
forgot password
</Link> 

the state object will retrive using

props.history.location.state




回答2:


Like that?

<Link to={`/restaurants/${meetup.venue.lat},${meetup.venue.lon}`}>Find Restaurants</Link>



回答3:


If you are using react-router v2 you could pass the location with the URL query string by using the <Link to={object} /> notation (Docs). See example below:

<Link to={{
    pathname: '/restaurants',
    search: `?lat=${meetup.venue.lat}&lon=${meetup.venue.lon}`
}} />

Within your Restaurants component you can access those properties within the props.history object (Example: history.location.search)



来源:https://stackoverflow.com/questions/48291678/how-to-pass-props-to-link-in-react-router-react-js-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!