我想你在找什麼東西等反應,終極版。這允許您連接組件以依賴狀態樹的一部分,並且只要狀態發生更改(只要您應用新的引用)就會更新。請看下圖:
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組件進行渲染。
這是一種天真的方法,但我相信它說明了解決方案並使您走上正軌!
祝你好運,希望這有助於!
阻止你在某些HOC/Aga/Thunk中收聽websocket? – Patrick
你有一些如何做到這一點的例子..我正在研究HOC和thunk現在...謝謝! –