React Router v4 和 v5

了解 Sentry 的 React Router v4 / v5 集成。

确保你使用 Router 组件结合 createBrowserHistory(或等效组件)。

为了获得参数化事务名称(例如,/teams/:teamid/user/:userid 而不是 /teams/123/user/345),你必须显式设置你想要参数化的路由。这是因为 React Router v4/v5 中没有 SDK 可以使用的静态路由配置。

我们建议你使用 withSentryRouting 高阶组件创建一个 SentryRoute 组件,在渲染时更新匹配路径。

Copied
import {Route, Router, Switch } from 'react-router-dom';
import { createBrowserHistory } from 'history';

import * as Sentry from '@sentry/react';

// Create Custom Sentry Route component
const SentryRoute = Sentry.withSentryRouting(Route);

const history = createBrowserHistory();

Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  integrations: [
    Sentry.reactRouterV5BrowserTracingIntegration({ history }),
    // OR
    Sentry.reactRouterV4BrowserTracingIntegration({ history }),
  ],

  // We recommend adjusting this value in production, or using tracesSampler
  // for finer control
  tracesSampleRate: 1.0,
});

render() {
  return (
    <Router history={history}>
      <Switch>
        <SentryRoute path="/users/:userid" component={() => <div>UserId</div>} />
        <SentryRoute path="/users" component={() => <div>Users</div>} />
        <SentryRoute path="/" component={() => <div>Home</div>} />
      </Switch>
    </Router>
  );
}

如果你不想包装单个路由,你仍然可以手动指定参数化路由,方法是传递一个路由配置对象数组(根据 react-router-config)到仪器函数调用中。你还需要提供从 react-router-domreact-router 包导出的 matchPath 函数。

Copied
import { Route, Router, Switch, matchPath } from 'react-router-dom';
import { createBrowserHistory } from 'history';

import * as Sentry from '@sentry/react';

const history = createBrowserHistory();

// Array of Route Config Objects
// Make sure the order of the routes is correct. The longest url under the same parent should be placed first and in decreasing order.
const routes = [{ path: '/users/:userid' }, { path: '/users' }, { path: '/' }];

Sentry.init({
  dsn: "https://examplePublicKey@o0.ingest.sentry.io/0",
  integrations: [
    Sentry.reactRouterV5BrowserTracingIntegration({
      history,
      routes,
      matchPath
    }),
  ],

  // We recommend adjusting this value in production, or using tracesSampler
  // for finer control
  tracesSampleRate: 1.0,
});

// In your App render:
render() {
  return (
    <Router history={history}>
      <Switch>
         <Route path="/users/:userid" component={() => <div>UserId</div>} />
         <Route path="/users" component={() => <div>Users</div>} />
         <Route path="/" component={() => <div>Home</div>} />
      </Switch>
    </Router>
  );
}