简体   繁体   English

通过嵌套路线reactJS传递道具

[英]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: TableRoute组件如下:

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 /> . 我的问题是将bedData传递给<Component /> I have checked with debugging and the and the bedData is passed to the Route component inside the TableRoute class. 我曾与调试和检查,并在bedData传递给Route内部组件TableRoute类。

My final goal is to get the bedData as props into the <TableView /> Component. 我的最终目标是将bedData作为道具添加到<TableView />组件中。

However, I cannot comprehend how to pass this as props to the <Component /> . 但是,我无法理解如何将此作为道具传递给<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. 我对React也很陌生,所以这也可能是新手愚蠢。 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 您正在将bedData传递到您的自定义路由,该路由在自定义路由中可以作为rest.bedData访问,您可以像这样传递给组件

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 }
    }} />
 )} />
)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM