【问题标题】:How to use MSAL-React with class component?如何将 MSAL-React 与类组件一起使用?
【发布时间】:2021-01-25 09:35:56
【问题描述】:

我在我的反应项目中使用https://www.npmjs.com/package/@azure/msal-react。该库提供了非常容易执行身份验证的钩子。

所以在功能组件中,为了获取访问令牌,

if (account && inProgress === "none") {
instance.acquireTokenSilent({
...loginRequest,
account: account
}).then((response) => {
callMsGraph(response.accessToken).then(response => setGraphData(response));
});
}

需要在使用const { instance, accounts, inProgress } = useMsal(); 的地方调用。

但是我需要调用 api 从类组件中获取数据。 那么,如何在类组件中实现同样的功能

【问题讨论】:

    标签: reactjs msal


    【解决方案1】:

    您无法访问类组件中的 msal-react 挂钩,因此您需要 access the raw context 或使用 higher order component 包装。

    以下内容取自文档中的示例,修改为您关于访问instance, accounts, inProgress 以进行后续 API 调用的问题。

    使用原始上下文

    import React from "react";
    import { MsalContext } from "@azure/msal-react";
    
    class YourClassComponent extends React.Component {
    static contextType = MsalContext;
    
    render() {
        const msalInstance = this.context.instance;
        const msalAccounts = this.context.accounts;
        const msalInProgress = this.context.inProgress;
        // rest of your render code
        }
    }
    

    }

    使用高阶组件

    import React from "react";
    import { withMsal } from "@azure/msal-react";
    
    class YourClassComponent extends React.Component {
        render() {
            const msalInstance = this.props.msalContext.instance;
            const msalAccounts = this.props.msalContext.accounts;
            const msalInProgress = this.props.msalContext.inProgress;
            // rest of your render code
        }
    }
    
    export default YourWrappedComponent = withMsal(YourClassComponent);
    

    无论哪种方式都有效,因此确实是个人喜好。为了可读性,我更喜欢访问原始上下文而不是包装。

    【讨论】:

      猜你喜欢
      • 2021-05-22
      • 2019-07-31
      • 2020-01-18
      • 1970-01-01
      • 2021-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多