2017-05-10 37 views
1

這裏是我的使用情況:反應,和/終極版的WebSockets和定時器動作

我有兩個不同的應用程序,反應客戶端應用程序,並表示爲REST API的/節點後端服務器應用程序。每次服務器在套接字上發送一個事件時,服務器端的數據發生更改,我希望響應客戶端應用程序刷新組件狀態。

我已經看到了websocket這樣做的例子(http://www.thegreatcodeadventure.com/real-time-react-with-socket-io-building-a-pair-programming-app/),但在這種情況下,客戶端和服務器組件都在同一個應用程序中。當您爲客戶端和服務器組件使用不同的應用程序時如何執行此操作。

如果數據有任何變化,我應該使用Timer(https://github.com/reactjs/react-timer-mixin)從客戶端調用服務器休息端點,並刷新客戶端上的組件。抑或終極版中間件提供這些功能..

感謝,拉傑什

+0

阻止你在某些HOC/Aga/Thunk中收聽websocket? – Patrick

+0

你有一些如何做到這一點的例子..我正在研究HOC和thunk現在...謝謝! –

回答

2

我想你在找什麼東西等反應,終極版。這允許您連接組件以依賴狀態樹的一部分,並且只要狀態發生更改(只要您應用新的引用)就會更新。請看下圖:

UserListContainer.jsx

import React, { Component } from 'react'; 
import { connect } from 'react-redux'; 
import * as UserActions from '../actions/userActions'; 
import UserList from '../components/UserList'; 

class UserListContainer { 
    // Subscribe to changes when the component mounts 
    componentDidMount() { 
    // This function 
    this.props.UserActions.subscribe(); 
    } 

    render() { 
    return <UserList {...props} /> 
    } 
} 

// Add users to props (this.props.users) 
const mapStateToProps = (state) => ({ 
    users: state.users, 
}); 

// Add actions to props 
const mapDispatchToProps =() => ({ 
    UserActions 
}); 

// Connect the component so that it has access to the store 
// and dispatch functions (Higher order component) 
export default connect(mapStateToProps)(UserListContainer); 

UserList.jsx

import React from 'react'; 

export default ({ users }) => (
    <ul> 
    { 
     users.map((user) => (
     <li key={user.id}>{user.fullname}</li> 
    )); 
    } 
    </ul> 
); 

UserActions.js

const socket = new WebSocket("ws://www.example.com/socketserver"); 

// An action creator that is returns a function to a dispatch is a thunk 
// See: redux-thunk 
export const subscribe =() => (dispatch) => { 
    socket.onmessage = (event) => { 
    const data = JSON.parse(event.data); 
    if (data.type === 'user add') { 
     // Dispatch ADD_USER to be caught in the reducer 
     dispatch({ 
     type: 'ADD_USER', 
     payload: { 
     data.user 
     } 
     }); 
    } 
    // Other types to change state... 
    }; 
}; 

說明

本質上正在發生的事情是,當容器組件安裝將會派遣subscribe行動,那麼這將爲從插座消息中列出。當它收到一條消息時,它會派遣另一個類型的動作庫,並將相應的數據發送到reducer中並添加到狀態中。 *注意:不要改變狀態,否則組件在連接時不會反映更改。

然後,我們使用react-redux來連接容器組件,它將狀態和動作應用於道具。所以現在任何時候users狀態都會改變,它會將它發送到容器組件並下到UserList組件進行渲染。

這是一種天真的方法,但我相信它說明了解決方案並使您走上正軌!

祝你好運,希望這有助於!

+0

謝謝,這很有用。你有一個服務器端代碼的簡短片段,如何接收事件,並在服務器端訂閱由客戶端發送的事件... –

+0

我可以指出你在正確的方向。如果你想快速查找socket.io,有很多關於如何做到這一點的教程。一個簡單的例子是http://ourcodeworld.com/articles/read/272/how-to-use-socket-io-properly-with-express-framework-in-node-js –

相關問題