我认为您正在寻找的是 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 组件进行渲染。
这是一种幼稚的方法,但我相信它说明了解决方案并让您走上正轨!
祝你好运,希望对你有所帮助!