gpt4 book ai didi

javascript - React-native Redux socket.io session 认证

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:41:38 25 4
gpt4 key购买 nike

关于将 redux/react-native 连接到 socket.io 的任何建议 after 一个 http 请求?我需要先发出 http 请求以存储身份验证 session cookie,然后连接到 socket.io。我见过的所有示例(即 https://www.npmjs.com/package/redux-socket.io)都会立即连接到 socket.io。我的想法是在自定义 redux 中间件中听取 Action 并像这样连接:

import React from 'react-native'
import * as actions from './actions/';
import io from 'socket.io-client/socket.io';

export default socketMiddleware = (store) => {
return next => action => {
const result = next(action);
// var socket = io();
//
if (action.type === 'HTTP_CONNECT_SUCCEEDED') {
debugger;
const socket = io('localhost:3000', {jsonp: false);
socket.on('connect', function(){console.log('Connected!')});
}
//
// socket.on('message', data => {
// store.dispatch(actions.addResponse(data));
// });
//
// if (socket && action.type === actions.ADD_MESSAGE) {
// let messages = store.getState().messages;
// socket.emit('message', messages[messages.length -1]);
// }

return result;
};
}

这适用于连接,但我必须在“HTTP_CONNECT_SUCCESS”条件中定义我的套接字,因此我的其他套接字操作和事件在该操作发生之前是未定义的。我如何连接到 WS 上的操作并公开我的套接字事件和其他操作?

最佳答案

我的希望临时技巧是使我的套接字变量成为全局变量,并将事件包装在条件中:

import React from 'react-native'
import * as actions from './actions/';
import io from 'socket.io-client/socket.io';

export default socketMiddleware = (store) => {
return next => action => {

const result = next(action);
globalSocket = typeof globalSocket === 'undefined' ? false : globalSocket

if (action.type === 'HTTP_CONNECT_SUCCEEDED') {
globalSocket = io('http://localhost:3000', {jsonp: false});
globalSocket.on('connect', () => {
console.log('Connected!')
});
}

if (globalSocket != false) {
globalSocket.on('friends', data => {
store.dispatch(actions.updateFriends(data));
})

if (action.type === 'CREATE_QUESTION') {
globalSocket.emit('createQuestion', action.question);
}
}

return result;
};
}

关于javascript - React-native Redux socket.io session 认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36816875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com