首页 > 解决方案 > 我可以使用 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 )

这种方法正在奏效。但我不确定这是否是获取实时数据的正确方法。

有没有其他我可以研究的方法。

标签: reactjsreduxreact-reduxredux-thunk

解决方案


推荐阅读