私はReact Nativeで新しく、奇妙な問題があります。ReactネイティブWebsocket onmessageは一度だけ起動します
2つのコンポーネントVisitor
とVisitor Chat Details
があります。 Visitor
に接続し、websocketに接続してVisitor Chat Details
にwebsocketを送信します。
私はVisitor
とVisitor Chat Details
の両方のメッセージを聞きます。 Visitor
のコンポーネントがメッセージを聞くとうまくいきます。しかし、コンポーネントをVisitor Chat Details
に変更すると、Visitor
コンポーネントのonmessage
イベントが無効になります。 Visitor Chat Details
の作業イベントのみ。ここで
export class VisitorListScreen extends React.Component {
constructor(props) {
super(props);
this.state = { isConnected: false, ws: null, fullname: '', username: '', alias: '', userId: null, hash: '', status: true, users: [] }
...
this.connect = this.connect.bind(this);
this.connectClient = this.connectClient.bind(this);
}
componentDidMount() {
...
this.connect();
}
connect() {
const SERVER_ID = createServerId();
const CONNECTION_ID = createConnectionId();
var ws = new WebSocket('wss://myurl.com/im/websocket');
this.setState({ ws: ws });
ws.onopen =() => {
// connection opened
console.log("connected")
this.setState({ isConnected: true });
};
ws.onmessage = e => {
console.log("listening");
// a message was received
this.handleMessage(e.data);
};
ws.onerror = e => {
// an error occurred
console.log("An error occured");
};
ws.onclose = e => {
// connection closed
console.log("connection closed");
this.setState({ isConnected: false });
TimerMixin.setTimeout(() => {
if (!this.state.isConnected) {
console.log("Reconnecting...");
this.connect();
}
}, 5000);
}
}
handleMessage(data) {
...
}
connectClient(user) {
this.props.navigation.navigate('VisitorDetail', { user: user, agentFullname: this.state.fullname, agentId: this.state.userId, ws: this.state.ws });
}
...
そしてビジターチャット詳細コンポーネント
export class VisitorDetail extends React.Component {
constructor(props) {
super(props);
const params = this.props.navigation.state.params;
let isServing = params.user.servingAgent != null && params.user.servingAgent == params.agentFullname;
this.state = { isServing:isServing, agentFullname: '', username: '', alias: '', agentId: '', hash: '', typing: '', user: params.user, ws: params.ws, messages: [] };
this.sendMessage = this.sendMessage.bind(this);
this.loadMessages = this.loadMessages.bind(this);
this.registerRoom = this.registerRoom.bind(this);
this.handleMessage = this.handleMessage.bind(this);
this.startChat = this.startChat.bind(this);
this.state.ws.onmessage = e => {
console.log("visitor detail listening");
console.log(e.data);
//this.handleMessage(e.data);
}
}
componentWillMount() {
..
}
componentDidMount() {
this.loadMessages();
this.registerRoom();
}
loadMessages() {
const siteId = 'cc76df43-da21-4b62-81be-4868b11c43dc';
...
}
registerRoom() {
...
}
startChat(){
これを修正し、2つのコンポーネントでwebsocketを聞くにはどうすればいいですか? – user2542467
[Observer design pattern](https://www.google.com.br/search?q=react+observer+design+pattern)を実装することをお勧めします。 )。 – Matruskan