【问题标题】:Passing an Instance of a Service Through a Route in React在 React 中通过路由传递服务实例
【发布时间】:2017-04-13 20:19:47
【问题描述】:

在这种情况下,我正在使用 react router v4,这很重要。

我有一个 App 组件,其中成功实例化了一个 AuthService 对象。

我想获取相同的 Auth 对象实例的某些组件,并且这些组件是通过 Route 定义的。

这是我的代码示例:

const auth = new AuthService();

class App extends Component {

  render() {
    return (
      <div>
        <ul>
          <li><Link to="/">Home</Link></li>
          <li><Link to="/splash">Login</Link></li>
        </ul>
        <Route exact path="/" component={Home} auth={auth}/>
        <Route exact path="/splash" component={SplashPage} auth={auth}/>
      </div>
    );
  }
}

export default App;

当 Home 或 SplashPage 渲染时,它们具有 Route 的典型 props,但没有 auth 意识。

如何将身份验证作为道具之一,以及来自 Route down to Home 和 SplashPage 的那些道具?谢谢。

【问题讨论】:

    标签: javascript reactjs react-router react-router-v4


    【解决方案1】:

    您可以使用路由render 函数并将身份验证作为道具传递给需要身份验证的组件。

    <Route {...routeConfig here} render={props => (
          <Home {...props} auth={auth}/>
    )}/>
    

    通过这种方式,您可以传递组件所需的自定义道具。 这是文档的link。

    【讨论】:

    • 如果我想创建一个 AuthRoute,这样我就可以使用它来渲染任何需要 auth 实例的组件?到目前为止我有这么多... const AuthRoute = ({ component, ...rest }) => { return ( { return React.createElement(component , 道具); }}/> ) }
    • 用这个解决了最后一点:React.createElement(component, {...props, auth});仍然是菜鸟的标志,传播操作员对我来说仍然是神秘而神奇的。 :)
    • 我当时也有类似的情况。渲染不适用于 react-router v2 中的路由。我的解决方案是使用组合组件。它帮助我包装我的组件以获得额外的行为。它看起来像&lt;Route path="/profile" component={AuthWrapper(Profile)} /&gt; 现在 AuthWrapper 是一个简单的包装器组件,如果遇到身份验证,它会呈现配置文件,否则它将用户带到登录页面。你可以阅读更多关于它here
    猜你喜欢
    • 2015-03-20
    • 2012-05-03
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    • 2017-07-05
    • 2016-10-14
    • 2021-09-13
    • 1970-01-01
    相关资源
    最近更新 更多