React JS集成Strophe连接XMPP服务器时出现未定义变量编译报错如何解决
问题解决方法
1. 解决$pres、$iq未定义报错
strophe.js 在模块化引入(React的CommonJS/ESModule引入模式)场景下,不会自动将$pres、$iq这类XML生成器挂载到全局作用域,你需要从Strophe实例上调用这两个方法:
把原代码里的对应行
connection.send($pres().tree()); connection.sendIQ($iq({ type: "get" }).c("query", { xmlns: Strophe.NS.ROSTER }).tree(), onRoster);
替换为
connection.send(Strophe.$pres().tree()); connection.sendIQ(Strophe.$iq({ type: "get" }).c("query", { xmlns: Strophe.NS.ROSTER }).tree(), onRoster);
也可以在引入阶段直接解构出需要的方法,简化后续调用:
const { Strophe, $pres, $iq } = require("strophe.js");
2. 解决onPresence未定义报错
你当前只注册了回调函数,但没有实现对应的函数定义,除了onPresence外,代码中用到的onMessage、onRoster也都需要提前定义,可以先写占位实现避免编译报错,后续再补充业务逻辑:
// 消息接收回调 function onMessage(msg) { console.log('收到消息:', msg); return true; // 保持handler持续生效 } // 出席状态回调 function onPresence(presence) { console.log('收到出席状态:', presence); return true; } // 花名册查询回调 function onRoster(result) { console.log('收到花名册数据:', result); }
额外优化建议
你当前把XMPP连接逻辑写在组件外层,会导致模块加载时就直接发起连接,不符合React组件的生命周期规范,建议放到useEffect钩子中,组件挂载时连接、卸载时断开,避免重复连接、内存泄漏问题:
import { useEffect } from 'react'; import './App.css'; const { Strophe, $pres, $iq } = require("strophe.js"); const BOSH_SERVICE = 'ws://chat.example.com:7070/ws'; function App() { useEffect(() => { Strophe.LogLevel = 0; const connection = new Strophe.Connection(BOSH_SERVICE, { 'keepalive': true }); function onConnect(status) { if (status == Strophe.Status.CONNECTING) { console.log('Synergy is connecting.'); } else if (status == Strophe.Status.CONNFAIL) { console.log('Synergy failed to connect.'); } else if (status == Strophe.Status.DISCONNECTING) { console.log('Synergy is disconnecting.'); } else if (status == Strophe.Status.DISCONNECTED) { console.log('Synergy is disconnected.'); } else if (status == Strophe.Status.CONNECTED) { console.log('Synergy is connected.'); connection.addHandler(onMessage, null, 'message', null, null, null); connection.send($pres().tree()); connection.addHandler(onPresence, null, "presence"); connection.sendIQ($iq({ type: "get" }).c("query", { xmlns: Strophe.NS.ROSTER }).tree(), onRoster); } } function onMessage(msg) { console.log('收到消息:', msg); return true; } function onPresence(presence) { console.log('收到出席状态:', presence); return true; } function onRoster(result) { console.log('收到花名册数据:', result); } connection.connect("rajan@example.com","jagruti", onConnect); // 组件卸载时断开连接 return () => { connection.disconnect(); } }, []) return ( <div className="App"> <p>Strophe React Example</p> </div> ); } export default App;
内容的提问来源于stack exchange,提问作者Rajan
相关产品推荐
相关产品推荐

