全局上下文

更新时间: 2024/03/26 18:08:14

概述

store 是基于 IM SDK 和 Mobx 封装的全局上下文。它提供 IM UIKit 内部数据驱动的能力,由 Mobx 提供数据和 UI 双向绑定的能力。您可以在 store 中获取各 IM 组件(例如会话组件、通讯录组件、聊天组件等)的上下文,或调用 store 上的一些方法完成您的自定义需求(例如发送自定义消息、场景群聊时添加扩展字段等)。

访问 store

IM UIKit 提供 useStateContext hooks 函数,帮助您在 Provider 的子组件访问 IM UIKit 的上下文。

在访问 store 前需要确保:

  • 完成 UIKit 的初始化。
  • react 框架保证 Provider 被执行。
  • vue 框架已完成 new IMUIKit(...) 的创建且已调用 this.$uikit.render(...)

useStateContext hooks 函数的返回值说明如下:

返回值 类型 说明
nim Object NIM SDK 实例的封装,开发者一般无需关心
store Object 内部 store,具体说明见下文的store 说明
initOptions Object 初始化时传入的初始化参数

示例代码:

React
import { useStateContext } from '@xkit-yx/im-kit-ui'

const { store, nim } = useStateContext()
Vue
<script lang="ts">
    const initOptions = {
     ...
    };
    const localOptions = {
      ...
    }
    // 初始化相关操作
    app.config.globalProperties.$uikit = new IMUIKit({
      initOptions,
      singleton: true,
      sdkVersion: 1,
      localOptions
    });
    this.$uikit.render(...);
    const { store, nim } = window.__xkit_store__
  },
};
</script>

调用 stroe 方法

如果需要使用store中的数据自行渲染,请使用 mobx-react 提供的 observer 包裹您的 React 组件。具体使用说明请参见 Mobx

store 的子 store 列表:

返回值 类型 说明
uiStore Object Mobx 可观察对象,负责 UI 会用到的属性的子 store
connectStore Object Mobx 可观察对象,负责连接的子 store
msgStore Object Mobx 可观察对象,负责管理会话消息的子 store
sysMsgStore Object Mobx 可观察对象,负责管理系统消息的子 store
sessionStore Object Mobx 可观察对象,负责管理会话列表的子 store
friendStore Object Mobx 可观察对象,负责管理好友信息的子 store
userStore Object Mobx 可观察对象,负责管理用户信息(包含陌生人)的子 store
relationStore Object Mobx 可观察对象,负责管理黑名单和静音列表的子 store
teamStore Object Mobx 可观察对象,负责管理群组的子 store
teamMemberStore Object Mobx 可观察对象,负责管理群组成员的子 store

例如您想在创建群聊的同时添加群扩展字段,可调用群组 store( teamStore)中的创建群组接口实现,具体参数请参考createTeamActive

示例代码:

reactstore.teamStore.createTeamActive({
    name: '测试群',
    avatar: 'https:xxxxxxxxxxx',
    accounts: ['account1', 'account2'],
    ext: JSON.stringify({ test: 'test' })
}).then(res => {
    console.log('======创建群成功=======');
    console.log(res);
}).catch(err => {
    console.log('======创建群失败=======');
    console.log(err);
})

使用原生 SDK 的 API

如果您需要自行实现目前 UIKit 还未实现的能力,且原生 IM Web SDK 已提供该能力。您可以通过调用原生 IM Web SDK 中提供的接口来实现。原生 IM Web SDK 中的接口请参考对应的 API 文档

例如,您想云端全文检索消息(按时间分页搜索),可以调用原生 IM Web SDK 中的msgFtsInServerByTiming 方法,示例代码如下:

React
import { useStateContext } from '@xkit-yx/im-kit-ui'
const { store, nim } = useStateContext()
nim.nim.msgFtsInServerByTiming({
  keyword: '你好',
  done:(err, data) => {
     console.log('======data======', data)
  }
})
Vue
const { store, nim } = window.__xkit_store__
nim.nim.msgFtsInServerByTiming({
  keyword: '你好',
  done:(err, data) => {
     console.log('======data======', data)
  }
})
此文档是否对你有帮助?
有帮助
去反馈
  • 概述
  • 访问 store
  • 调用 stroe 方法
  • 使用原生 SDK 的 API