我正在使用 React Native 和 Symfony 开发通知系统。我用 docker 配置 Mercure 来处理实时更新的前端订阅:.env 文件:
###> symfony/mercure-bundle ###
# See https://symfony.com/doc/current/mercure.html#configuration
MERCURE_PUBLISH_URL=http://mercure.localhost/.well-known/mercure
# The default token is signed with the secret key: !ChangeMe!
MERCURE_JWT_TOKEN=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXJjdXJlIjp7InB1Ymxpc2giOlsiKiJdfX0.9-LscFk3QfdDtZ4nyg6BiH4_qDm6pbYHydURBMsDgEc
###< symfony/mercure-bundle ###
美居.yaml:
mercure:
enable_profiler: '%kernel.debug%'
hubs:
default:
url: '%env(MERCURE_PUBLISH_URL)%'
jwt: '%env(MERCURE_JWT_TOKEN)%'
我在我的 React Native 应用程序中创建了一个通知组件,并使用了 symfony mercure 官方文档中的代码: https ://symfony.com/doc/4.3/mercure.html#subscribing Notifications.js 代码:
import React, { Component } from 'react';
import { View, Text } from 'react-native';
export default class Notifications extends Component {
constructor(props) {
super(props);
this.state = {
};
}
componentDidMount() {
const url = new URL('http://mercure.localhost/.well-known/mercure');
url.searchParams.append('topic', 'http://dev.api.partage-mandats.proprietes-privees.com/mandate_shares/{id}');
url.searchParams.append('topic', 'http://example.com/books/1');
const eventSource = new EventSource(url);
eventSource.onmessage = e => console.log(e);
}
render() {
return (
<View>
<Text> Notifications </Text>
</View>
);
}
}
我尝试了 html 文件中的 javaScript 代码进行测试:
<script type="text/javascript">
const url = new URL('http://mercure.localhost/.well-known/mercure');
url.searchParams.append('topic', 'http://dev.api.partage-mandats.proprietes-privees.com/mandate_shares/{id}');
url.searchParams.append('topic', 'http://example.com/books/1');
const eventSource = new EventSource(url);
eventSource.onmessage = e => console.log(e);
</script>
</html>
当我使用 Postman 运行请求时,我得到了实时响应: 我的问题是 URL、searchParams 和 eventSource 与本机反应不兼容。如何转换此 JavaScript 代码以响应本机有效代码?我尝试安装一些库:whatwg-url、buffer、react-native-event-source,我当前的代码是:
import React, { Component } from 'react';
import { View, Text } from 'react-native';
import { URL, URLSearchParams } from 'whatwg-url';
import { Buffer } from 'buffer';
import RNEventSource from 'react-native-event-source';
export default class Notifications extends Component {
constructor(props) {
super(props);
this.state = {
};
}
componentDidMount() {
global.Buffer = Buffer;
global.URL = URL;
global.URLSearchParams = URLSearchParams;
global.EventSource = RNEventSource;
const url = new global.URL('http://mercure.localhost/.well-known/mercure');
url.global.URLSearchParams.append('topic', 'http://dev.api.partage-mandats.proprietes-privees.com/mandate_shares/{id}');
url.global.URLSearchParams.append('topic', 'http://example.com/books/1');
const eventSource = new global.EventSource(url);
eventSource.onmessage = e => console.log(e);
}
render() {
return (
<View>
<Text> Notifications </Text>
</View>
);
}
}
我得到了这个错误:未定义不是一个对象(评估'url.global.URLSearchParams')