简体   繁体   中英

Passing props through nested route reactJS

I have an app that uses a custom router.

In my root App I have the following code (not the full code):

class ViewerApp extends Component {
    render() {
    return (
      <Router>
        <Route path="/" exact render={()=> <Redirect to={{pathname: '/login'}}/>}/>
        <Route path="/login" exact component={Login}/>
        <TableRoute path='/table' exact component={TableView} bedData={this.state.bedData}/>
      </Router>
    )
  }
}

The TableRoute component is as follows:

export const TableRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={(props) => (
    authenticator.isAuthenticated === true
      ? <Component {...props} bedData={[]}/>
      : <Redirect to={{
          pathname: '/xxxx',
          state: { from: props.location }
        }} />
  )} />
)

This line works fine, as well as the redirect. My problem is with passing bedData to the <Component /> . I have checked with debugging and the and the bedData is passed to the Route component inside the TableRoute class.

My final goal is to get the bedData as props into the <TableView /> Component.

However, I cannot comprehend how to pass this as props to the <Component /> . I have already tried as shown above with

<Component {...props} bedData={[]}/>

and with

<Component {...props} />

as I thought it should get passed with the direct props, but nothing worked. i am quite new to React too, so this could be newbie stupidity too. Thanks in advance.

You are passing bedData to your custom Route which is accessable in custom Route as rest.bedData which you can pass on to your components like this

export const TableRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={(props) => (
     authenticator.isAuthenticated === true
  ? <Component {...props} bedData={rest.bedData}/>
  : <Redirect to={{
      pathname: '/xxxx',
      state: { from: props.location }
    }} />
 )} />
)

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