You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过一次函数调用给多个用户发送Expo推送通知?

批量发送Expo推送通知的解决方案

问题核心

你当前能给单个用户发送推送,但批量发送失败,原因是Expo推送API要求批量发送时to字段必须是数组类型,而你传入的是拼接后的字符串。

解决步骤

  1. 将字符串格式的tokens转换为数组:你接收的pushTokens是每行一个token的字符串,需要先分割、清理成纯净的token数组。
  2. 修改消息体的to字段为数组:替换原来的字符串,改用处理后的数组。
  3. 修复代码中的小问题:比如组件嵌套错误、函数参数冗余、添加错误排查逻辑。

修改后的完整代码

const Notification = ({ pushTokens }) => {
  // 处理字符串tokens,转换为有效token数组
  const formattedTokens = pushTokens
    .split('\n') // 按换行分割成单个token项
    .map(item => item.replace('token: ', '').trim()) // 去除前缀和多余空格
    .filter(token => token.startsWith('ExponentPushToken')); // 过滤掉无效token

  const message = {
    to: formattedTokens, // 批量发送必须传入数组
    sound: 'default',
    title: 'title',
    body: 'body',
  };

  function notificationButton() {
    fetch('https://exp.host/--/api/v2/push/send', {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Accept-encoding': 'gzip, deflate',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(message),
    })
    .then(res => res.json())
    .then(data => console.log('推送结果:', data))
    .catch(err => console.error('推送出错:', err));
  }

  return (
    <TouchableOpacity onPress={notificationButton}>
      <Text> Notification Button </Text>
    </TouchableOpacity>
  );
};

关键说明

  • 字符串转数组:split('\n')把每行的token拆分出来,replace去掉多余的"token: "前缀,filter确保只保留符合Expo格式的有效token,避免无效值导致推送失败。
  • to字段的类型要求:Expo的/push/send接口,单个用户传字符串,多个用户必须传字符串数组,这是批量发送的核心要求。
  • 错误处理:添加then/catch可以在控制台看到推送的具体结果,方便排查问题(比如token无效、接口权限问题等)。
  • 组件修复:原代码里返回的Notification组件会和当前组件重名,换成React Native标准的TouchableOpacity可点击组件,避免冲突。

内容的提问来源于stack exchange,提问作者john_1

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 20:54:17