Home > @elux/react-taro > getApi

getApi() function

获取应用全局方法

Signature:

export declare function getApi<TAPI extends {
    State: any;
    GetActions: any;
    LoadComponent: any;
    GetComponent: any;
    GetData: any;
    Modules: any;
}>(demoteForProductionOnly?: boolean, injectActions?: Record<string, string[]>): Pick<TAPI, 'GetActions' | 'LoadComponent' | 'GetComponent' | 'GetData' | 'Modules'> & {
    GetClientRouter: () => IRouter;
    useRouter: () => IRouter;
    useStore: () => VStore<TAPI['State']>;
};

Parameters

ParameterTypeDescription
demoteForProductionOnlyboolean用于不支持Proxy的运行环境
injectActionsRecord<string, string[]>用于不支持Proxy的运行环境

Returns:

Pick<TAPI, 'GetActions' | 'LoadComponent' | 'GetComponent' | 'GetData' | 'Modules'> & { GetClientRouter: () => IRouter; useRouter: () => IRouter; useStore: () => VStore<TAPI['State']>; }

返回包含多个全局方法的结构体:

  dispatch(Modules.article.actions.refresh())
  • GetActions:当需要 dispatch 多个 module 的 action 时,例如:
  dispatch(Modules.a.actions.a1())
  dispatch(Modules.b.actions.b1())

这种写法可以简化为:

  const {a, b} = GetActions('a', 'b')
  dispatch(a.a1())
  dispatch(b.b1())
  • GetClientRouter:在CSR(客户端渲染)环境中用于获取全局Router。

  • useRouter:用于在 UI Render 中获取当前 Router,在CSR(客户端渲染)中其值等于GetClientRouter(),例如:

  const globalRouter = GetClientRouter()
  const currentRouter = useRouter()
  console.log(blobalRouter===currentRouter)
  • useStore:用于在 UI Render 中获取当前 Store,例如:
  const store = useStore()
  store.dispatch(Modules.article.actions.refresh())

Remarks

通常不需要参数,仅在兼容不支持Proxy的环境中需要传参

Example

const {Modules, LoadComponent, GetComponent, GetData, GetActions, GetClientRouter, useStore, useRouter} = getApi<API>();