简体   繁体   中英

How to pass props between React Routes 4

I can't find the way how to send object from one React Route Component to another. For example I have container router like this:

const App = () => (
  <Router>
    <div>
      <Route exact path="/" component={Home} />
      <Route path="/sections/:id" 
             component={Section} />
    </div>
  </Router>
)

with Home component like this:

const Home = () => {
    const Sections = tilesData.map( (section, index) => (
      <div>
        <img src={section.img} height="200" /><br/>
        <Link to={`/sections/'${section.id}`} >Details for {section.author}</Link>
        <hr/>
      </div>
    ))
    return(
      <div>
          {Sections}
      </div>
    )
}

and I don't understand =\\ how to pass selected object when next route clicked with <Link> . Here is example component:

const Section = (props) => {
    return(
        <div>
            Section {props.title} 
            <img src={props.img} />
        </div>
    )
}

Here is code example: https://codesandbox.io/s/Mv037AE3

In react-router v4, we usually do the following to pass in a ProductPage component:

<Route path='/' component={ProductPage} />

When you want to use props, you can prepare a function that returns your component with the desired props. Here I'm preparing to pass in a toggleSidebarOn prop:

const MyProductPage = (props) => {
  return (
    <ProductPage 
      toggleSidebarOn={this.toggleSidebarOn.bind(this)}
      {...props}
    />
  );
}

Then you use the render prop of the <Route /> instead of its component prop. Do not use both and do not use the component prop as this leads to undesired remounting and might break your app (eg for me CSS transitions for the sidebar animation stopped working properly).

Using the render prop for the MyProductPage we can then pass in our toggleSidebarOn prop to its target route:

<Router>
  <div>
    <Switch>
      <Route exact path="/products" render={MyProductPage} />
      <Route exact path="/perspectives" component={PerspectivePage}/>
      <Route component={NotFound}/>
    </Switch>
  </div>
</Router>

Hope this helps!

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