reactjs - 我可以使用 Redux 获取实时数据吗
问题描述
我是 ReactJS 的新手,正在探索需要实时数据的应用程序。
假设我有“n”个组件必须显示实时数据(1 秒更新)。该应用程序应整合所有“n”个组件的相关“标签”并调用为所有“标签”提供实时数据的网络服务器(我无法从每个组件进行调用,因为这将是一个巨大的负载。所以我必须合并并打一个电话)。
有一个组件“RealTimeDataFetcher”,它有一个计时器并每秒调用一个动作“GETLIVEDATA”。此操作调用 web 服务并返回响应(使用 thunk)。DataReducer 返回更新后的状态,所有“n”个组件都使用 MapStateToProps 来获取实时数据。
行动
export const subscribeForData = tag =>{
return {type : 'SUBSCRIBE' , payload : tag}
}
export const getLiveData = tag[] =>{
const response = await makeServiceCall(tag[]);
dispatch({ type: 'LIVE_DATA', payload: response.data });
}
减速器
export const liveData = (livedata, action){
// update state for live data
}
export const subscribedTags= (tags, action){
// update state for subscribed tags
}
实时数据提取器
class RealTimeDataFetcher extends React.Component{
componentDidMount(){
// call subscribeData for fetching livedata for "tags"
}
}
function mapStateToProps (state){
return { subscribedTags: state.subscribedTags};
}
connect(mapStateToProps,{...})(RealTimeDataFetcher)
零件
class SomeComponent extends React.Component{
ComponentDidMount(){
this.props.subscribeForData("tag");
}
ComponentDidUpdate(){
// I will get the live data here.
}
}
function mapStateToProps (state){
return { liveData: state.liveData};
}
connect(mapStateToProps,{...})(SomeComponent )
这种方法正在奏效。但我不确定这是否是获取实时数据的正确方法。
有没有其他我可以研究的方法。
解决方案
推荐阅读
- android - 取消 (image_picker) 活动时,Flutter 在 Android 上崩溃
- android - 使用 setupWithViewPager 时 XML TabItem 消失了
- php - WooCommerce COD 根据购物车金额收费
- java - 如何使用带有“java/eclipse”的 lambda 函数将 csv 文件加载到 postgres 数据库
- graphql - 在 GraphQL 查询中过滤结果
- javascript - 使用 Sheetjs 和 FileReader.js 将 XLS 转换为 JSON
- entity-component-system - 实体组件系统中的初学者
- python - 调试代码以打印字数:类型错误:图像数据无法转换为浮点数
- sql - Sql查询捕获最小日期,基于行排序的最大日期为空
- ionic-framework - 当我在 Windows 上运行 ionic 应用程序时,它显示错误:找不到模块“@angular/compiler”