首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在类组件中使用MSAL-React?

如何在类组件中使用MSAL-React?
EN

Stack Overflow用户
提问于 2021-01-25 17:35:57
回答 1查看 629关注 0票数 0

我在我的react项目中使用https://www.npmjs.com/package/@azure/msal-react。该库提供了钩子,可以非常轻松地执行身份验证。

因此在功能组件中,为了获取访问令牌,

代码语言:javascript
复制
if (account && inProgress === "none") {
instance.acquireTokenSilent({
...loginRequest,
account: account
}).then((response) => {
callMsGraph(response.accessToken).then(response => setGraphData(response));
});
}

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

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

EN

回答 1

Stack Overflow用户

发布于 2021-03-01 19:35:25

您不能访问类组件中的msal-react挂钩,因此要做到这一点,您需要使用access the raw context,或者使用higher order component进行包装。

以下是文档中的示例,针对您的后续接口调用访问instance, accounts, inProgress的问题进行了修改。

使用原始上下文的

代码语言:javascript
复制
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
    }
}

}

使用高阶分量

代码语言:javascript
复制
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);

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65882141

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档