2017-10-12 115 views
1

我正在使用react-router,并创建了一个PrivateRoute组件,该组件在验证后显示组件,否则重定向到登录页面。如何在反应中添加另一个道具...道具

我想要做的是传递一个额外的道具(认证)在调用者指定的顶部。

我似乎无法得到正确的语法,并搜索“...道具”没有提出任何文档。

这里是我的代码:

const PrivateRoute = ({ component: Component, ...rest }) => (
      <Route {...rest} render={(props) => (
       this.state.authentication.authenticated() ? (
        <Component authentication:{this.state.authentication} {...props}/> 
       ) : (
        <Redirect to={{ 
         pathname: '/login', 
         state: { from: props.location } 
        }}/> 
       ) 
      )}/> 
     ); 

回答

2

问题是authentication道具语法。用=代替:

<Component authentication={this.state.authentication} {...props}/> 
1

这将是就像任何其他的道具:

<Component 
    authentication={this.state.authentication} 
    {...props} 
/> 

我觉得它有助于把它们放在单独的行很容易地看到发生了什么。

另外,如果{...props}已经包含了一个名为authentication键,那么你可以通过把它经过重写它:

const someProps = { 
    hello: 1 
}; 

// this.props.hello will be 2 
<Component 
    {...someProps} 
    hello={2} 
/>