2016-04-23 160 views
4

任何關於連接redux/react-native與socket.io 之後的任何建議 http請求?我需要首先使http請求存儲auth會話cookie,然後連接到socket.io。我見過的所有例子(即https://www.npmjs.com/package/redux-socket.io)都立即連接到socket.io。我的想法是聽的動作和定製終極版中間件連接,像這樣:React-native Redux socket.io會話身份驗證

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,並公開我的套接字事件和其他動作?

回答

0

希望臨時黑客是讓我的插座變量全球,並在有條件的包裹事件:

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; 
    }; 
} 
+0

邊際改善,但你可以使用一個'var'而是一個全球性的,即'變種socket = null'而不是'globalSocket = typeof ...'。然後在你的'if(action.type ==='HTTP_CONNECT_SUCCEEDED')'你設置'socket',然後降低你將if(globalSocket!= false)'改爲'if(socket)'。 – BarthesSimpson