Context コンテキスト

NocoBase では、コンテキスト(Context) はプラグインコードと NocoBase の機能をつなぐ橋渡し役です。コンテキストを通じて、リクエスト送信、国際化、ログ出力、ページナビゲーションなどが行えます。

コンテキストには2つのアクセス方法があります:

  • Plugin 内this.context
  • React コンポーネント内useFlowContext()@nocobase/flow-engine からインポート)

これら2つが返すのは同一のオブジェクトFlowEngineContext インスタンス)であり、使用シーンが異なるだけです。

Plugin 内での使用

プラグインの load() などのライフサイクルメソッド内で、this.context 経由でアクセスします:

import { Plugin } from '@nocobase/client-v2';

class MyPlugin extends Plugin {
  async load() {
    // this.context 経由でコンテキスト機能にアクセス
    const { api, logger } = this.context;

    const response = await api.request({ url: 'app:getInfo' });
    logger.info('アプリケーション情報', response.data);

    // 国際化:this.t() はプラグインのパッケージ名を namespace として自動注入
    console.log(this.t('Hello'));
  }
}

コンポーネント内での使用

React コンポーネント内では、useFlowContext() で同じコンテキストオブジェクトを取得します:

import { useFlowContext } from '@nocobase/flow-engine';

export default function MyPage() {
  const ctx = useFlowContext();

  const handleClick = async () => {
    const response = await ctx.api.request({ url: 'users:list', method: 'get' });
    console.log(response.data);
  };

  return <button onClick={handleClick}>{ctx.t('Load data')}</button>;
}

Plugin ショートカットプロパティ vs ctx プロパティ

Plugin クラスにはいくつかのショートカットプロパティがあり、load() 内で便利に使えます。ただし、Plugin クラスのショートカットプロパティと ctx 上の同名プロパティが異なるものを指す場合があるので注意が必要です:

Plugin ショートカットプロパティ指す先用途
this.routerRouterManagerルートの登録。.add() を使用
this.pluginSettingsManagerPluginSettingsManagerプラグイン設定ページの登録(addMenuItem + addPageTabItem
this.flowEngineFlowEngine インスタンスFlowModel の登録
this.t()i18n.t() + 自動 ns国際化。プラグインのパッケージ名を自動注入
this.contextFlowEngineContextコンテキストオブジェクト。useFlowContext() と同一

最も混乱しやすいのは this.routerctx.router です:

  • this.router(Plugin ショートカットプロパティ)→ RouterManager、ルートの登録に使用(.add()
  • ctx.router(コンテキストプロパティ)→ React Router インスタンス、ページナビゲーションに使用(.navigate()
// Plugin 内:ルートの登録
async load() {
  this.router.add('hello', {
    path: '/hello',
    componentLoader: () => import('./pages/HelloPage'),
  });
}
// コンポーネント内:ページナビゲーション
const ctx = useFlowContext();
ctx.router.navigate('/hello'); // -> /v/hello

コンテキストが提供する共通機能

ここでは主な機能を一覧にしますが、一部は Plugin でのみ利用可能、一部はコンポーネントでのみ利用可能、一部は両方で使えるが書き方が異なります。

機能Plugin(this.xxxComponent(ctx.xxx説明
API リクエストthis.context.apictx.api使い方は同じ
国際化this.t() / this.context.tctx.tthis.t() はプラグインの namespace を自動注入
ログthis.context.loggerctx.logger使い方は同じ
ルート登録this.router.add()-Plugin のみ
ページ遷移-ctx.router.navigate()コンポーネントのみ
ルート情報this.context.locationctx.route / ctx.locationコンポーネント内での使用を推奨
ビュー管理this.context.viewerctx.viewerダイアログ / ドロワーを開くなど
FlowEnginethis.flowEngine-Plugin のみ

各機能の詳しい使い方とコード例は共通機能をご覧ください。

関連リンク