React/Redux and Websockets for Timer actions



这是我的用例:

我有两个不同的应用程序,反应客户端应用程序和具有 REST API 的快速/节点后端服务器应用程序。我希望 react 客户端应用程序刷新组件状态,每次服务器在套接字上发送事件时,该事件在服务器端的数据发生了变化。

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

我是否应该使用计时器 (https://github.com/reactjs/react-timer-mixin) 从客户端调用服务器 rest 终结点,并在数据发生任何更改时刷新客户端上的组件。或者 redux 中间件是否提供了这些功能。

谢谢,拉杰什

我认为您正在寻找的是类似 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);

用户列表.jsx

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

用户操作.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操作,然后列出来自套接字的消息。 当它收到一条消息时,它将调度另一个基于其类型的操作,其中包含相应的数据,这些数据将被捕获到化简器中并添加到状态中。 *注意:请勿更改状态,否则组件在连接时不会反映更改。

然后我们使用 react-redux 连接容器组件,它将状态和动作应用于 props。 因此,现在每当users状态更改时,它都会将其发送到容器组件,并向下发送到UserList组件进行渲染。

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

祝你好运,希望这有帮助!

最新更新