我在我的react项目中使用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从类组件中获取数据。那么,如何在类组件中实现相同的功能呢?
发布于 2021-03-01 19:35:25
您不能访问类组件中的msal-react挂钩,因此要做到这一点,您需要使用access the raw context,或者使用higher order component进行包装。
以下是文档中的示例,针对您的后续接口调用访问instance, accounts, inProgress的问题进行了修改。
使用原始上下文的
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);无论哪种方式都有效,所以真的是个人喜好。为了可读性,我更喜欢访问原始上下文而不是包装。
https://stackoverflow.com/questions/65882141
复制相似问题