【问题标题】:AWS Amplify HOC Authenticator React does not pass authState property to wrapped componentAWS Amplify HOC Authenticator React 不会将 authState 属性传递给包装的组件
【发布时间】:2019-12-08 09:47:23
【问题描述】:

我正在尝试使用 Amplify Authenticator 在用户未登录时阻止对我的应用的访问。

 <Authenticator includeGreetings={true}>
            <Provider store={dataStore}>
                <Router history={hist}>
                    <MyView>
                    </MyView>
                </Router>
            </Provider>
        </Authenticator>

在我的组件 MyView 的渲染方法中,我试图通过以下方式进行简单的身份验证检查:

if (this.props.authState !== 'signedIn') {
            return (<></>);
        }

但由于某种原因,在 if 条件中检查 auth 状态时,它是未定义的。

  1. 为什么属性未定义 - 我在文档中了解到它正在向下传递到所有子组件。

    1. 我的方法正确吗?我从文档中看到您可以实现一个方法 showComponent(theme) 并且身份验证器只会在用户处于特定状态时调用它 但我需要在调用此方法时为身份验证器设置正确的状态 经过 this._validAuthStates = ['signedIn'];

但我不知道在哪里调用该方法,我无法在任何地方访问它。

我们将不胜感激。

【问题讨论】:

    标签: reactjs amazon-web-services amazon-cognito aws-amplify


    【解决方案1】:

    不是专家,但我遇到了这个问题,并以与您一样的方式与文档斗争。

    我偶然发现了一个解决方案

    在索引中,我以这种方式呈现我的组件

        <Provider store={store}>
          <Authenticator
              hide={[SignUp, SignIn, Greetings]}
          >
            <CustomGreetings/>
            <CustomSignUp/>
            <CustomSignIn/>
            <App/>
          </Authenticator>
        </Provider>
    

    在我的应用组件中,我现在可以访问authState。所以我将它重新注入到其他组件中:

    return(
      <Router>
        <NavbarComponent/>
        <Switch>
          <Route path="/dashboard">
            <DashboardContainer authState={this.props.authState}/>
          </Route>
          <Route path="/admin">
            <AdminComponent authState={this.props.authState}/>
          </Route>
        </Switch>
      </Router>
    );
    

    我不知道这是否是解决方案,但很好,对我来说它有效

    【讨论】:

    • 嗯,也许就像您的解决方案与我的解决方案一样,我需要另一个组件包装我的 组件来处理 authState,因为它只传递给包装组件,也许我必须有一个 组件,如您的示例或类似内容。谢谢!
    • 我正在尝试其他方法。我将尝试仅使用 Auth 方法而不是验证器。我认为,这可能更容易
    猜你喜欢
    • 2020-08-09
    • 2019-04-08
    • 2018-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-13
    相关资源
    最近更新 更多