【问题标题】:React/Redux and Websockets for Timer actions用于计时器操作的 React/Redux 和 Websockets
【发布时间】:2017-10-09 17:25:12
【问题描述】:

这是我的用例:

我有两个不同的应用程序,React 客户端应用程序和具有 REST API 的 express/node 后端服务器应用程序。我希望反应客户端应用程序刷新组件状态,每次服务器在套接字上发送一个事件,该事件在服务器端发生数据更改。

我已经看到了执行此操作的 websocket 示例 (http://www.thegreatcodeadventure.com/real-time-react-with-socket-io-building-a-pair-programming-app/),但在这种情况下,客户端和服务器组件位于同一个应用程序中。当您为客户端和服务器组件使用不同的应用程序时如何执行此操作。

如果数据有任何变化,我是否应该使用 Timer (https://github.com/reactjs/react-timer-mixin) 从客户端调用服务器休息端点并刷新客户端上的组件。或者 redux 中间件是否提供了这些功能..

谢谢,拉杰什

【问题讨论】:

  • 是什么阻止您在某些 HOC/Aga/Thunk 中收听 websocket?
  • 你有一些如何做的例子吗..我正在研究 HOC 和 thunk...谢谢!

标签: sockets reactjs redux react-redux


【解决方案1】:

我认为您正在寻找的是 react-redux 之类的东西。这允许您连接组件以依赖于状态树的一部分,并且在状态更改时会更新(只要您正在应用新的引用)。见下文:

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 连接容器组件,它将状态和动作应用于 props。因此,现在任何时候users 状态发生变化,它都会将其发送到容器组件,然后再发送到 UserList 组件进行渲染。

这是一种幼稚的方法,但我相信它说明了解决方案并让您走上正轨!

祝你好运,希望对你有所帮助!

【讨论】:

  • 谢谢,这很有用。您是否有服务器端代码的简短 sn-p,如何接收事件并在服务器端订阅客户端发送的事件...
  • 我可以为您指明正确的方向。如果你在 socket.io 上寻找 express 有很多关于如何做到这一点的教程。一个简单的例子是ourcodeworld.com/articles/read/272/…
猜你喜欢
  • 2021-10-05
  • 2015-11-23
  • 2020-02-25
  • 1970-01-01
  • 2019-02-08
  • 2018-12-05
  • 1970-01-01
  • 2022-11-01
  • 1970-01-01
相关资源
最近更新 更多