React 中的 ApplicationInsights

ApplicationInsights in React

我对应用程序洞察还很陌生,我正试图在我的 React 应用程序上获得它 运行 从这个意义上说,有一个包装器组件启动配置/连接到应用程序洞察服务。

当我实例化 Wrapper-Component 并嵌套另一个组件时,该组件应该可以访问 appInsights 对象(使 trackEvent、-trace、-error 方法可用),在其中,子组件声明 appInsights 是未定义。

所以本质上,简化后的组件结构看起来像这样:

<WrapperService> // initializes appInsights
  <ChildComponent> // should have access to the appInsights-Object in Order to fire Events
</WrapperService>

具体说明手头的目标:我如何传递 appInsights 对象以便能够在我想要的任何组件中使用它?

还有其他建议吗?非常感谢!

尝试将应用程序洞察添加到您可以使用 React Hooks 的子组件中。

按照以下步骤实现:

在 React 中添加应用程序见解参考 here

在你的 React 应用程序中添加应用程序洞察后尝试创建上下文文件,如 AppInsightsContext.js

import React, { createContext } from "react";
import { reactPlugin } from "./AppInsights";
const AppInsightsContext = createContext(reactPlugin);
const AppInsightsContextProvider = ({ children }) => {

    return (
        <AppInsightsContext.Provider value={reactPlugin}>
        {children}
    </AppInsightsContext.Provider>
    );
};
export { AppInsightsContext, AppInsightsContextProvider };

现在,我们有一个组件可以设置 reactPlugin。我们需要将它添加到我们的 React 应用程序中。

Layout/index.js 文件中,我们需要将上下文设置为高。

const LayoutWithContext = ({ location, children }) => (
< AppInsightsContextProvider>
    <>
    <Headroom
        upTolerance={10}
        downTolerance={10}
        style={{ zIndex: "20", height: "6.5em" }} >
        
        < Header location={location} />
    < /Headroom>
    < Container text>{children}</Container>
    < Footer />
    </>
< /AppInsightsContextProvider>
);

上下文正在使用中,所有 children 组件都可以在我们的子组件中访问它。

如果您想使用 React 插件的 标准页面 交互跟踪,您可以将其与 HOC(高阶组件)

import React from "react";
import Headroom from "react-headroom";
import { Container } from "semantic-ui-react";
import Footer from "../Footer";
import Header from "../Header";
import "semantic-ui-css/semantic.min.css";
import { AppInsightsContextProvider } from "../../AppInsightsContext";
import withAppInsights from "../../AppInsights";

const Layout = withAppInsights(({ location, children }) => (
    <>
    <Headroom
    upTolerance={10}
    downTolerance={10}
    style={{ zIndex: "20", height: "6.5em" }} >
        <Header location={location} />
    </Headroom>
    <Container text>{children}</Container>
    <Footer />
    </>
));

const LayoutWithContext = ({ location, children }) => (
    <AppInsightsContextProvider>
        <Layout location={location} children={children} />
    </AppInsightsContextProvider>
);

export default LayoutWithContext;

将上下文公开为一个钩子

我们可以使用新的 Context-provided react 插件做的最后一件事是让它更容易访问,为此我们将使用 useContext Hook。要做到这一点,只需更新 AppInsightsContext.js:

const useAppInsightsContext = () => useContext(AppInsightsContext);

为跟踪事件创建挂钩参考 here

参考this article了解更多信息