【问题标题】:Feeding Azure Event Hub data to ReactJS将 Azure 事件中心数据提供给 ReactJS
【发布时间】:2021-06-19 08:54:50
【问题描述】:

我正在尝试从 Azure 事件中心读取数据并将其显示在使用 ReactJS 的简单 Web 应用程序上。我使用 Microsoft 的代码示例来读取 Azure 数据,这可以很好地独立运行。我有一个物联网温度传感器,每次传感器发送时,我都会从控制台中的函数接收值:
const consumerClient = new EventHubConsumerClient("$Default", 
connectionString, clientOptions);

async function getTemperature() {

consumerClient.subscribe({
  processEvents: async(events, context) => {
      for(const event of events){
         var temperature = event.body.temperature;
         var humidity = event.body.humidity;
         console.log(temperature);
         console.log(humidity);
      }
  },
  processError: async (err, context) => {
      console.log(`Error : ${err}`);
  }
});
}

getTemperature().catch((error) => {
   console.error("Error running sample:", error);
});

我现在希望在 ReactJS 组件中使用它,如下所示:

const returnTemperature = () => {
    return ( 
        <div className="environment">
            <p>The temperature is { temperature }&#176; Celcius.</p>
        </div>
     );
}

export default returnTemperature;

我是 ReactJS 的新手,每次更新 Azure 函数接收到的温度时,我无法理解如何更新网页上的值。我已经研究了 useState/useEffect 但没有任何工作。
有什么建议吗?
提前致谢, 杰夫

【问题讨论】:

    标签: javascript reactjs azure react-hooks azure-eventhub


    【解决方案1】:

    我假设您可以使用功能组件。

    const Temperature = () => {
      const [temperature, setTemperature] = useState();
      const consumerClient = new EventHubConsumerClient(
        "$Default",
        connectionString,
        clientOptions
      );
    
      const getTemperature = async () => {
        consumerClient.subscribe({
          processEvents: async (events, context) => {
            for (const event of events) {
              var temperature = event.body.temperature;
              var humidity = event.body.humidity;
              setTemperature(temperature);
              console.log(temperature);
              console.log(humidity);
            }
          },
          processError: async (err, context) => {
            console.log(`Error : ${err}`);
          },
        });
      };
    
      useEffect(() => {
        getTemperature().catch((error) => {
          console.error("Error running sample:", error);
        });
        return () => {
          // cleanUpFunction if applicable
          // consumerClient.unsubscribe()
        };
      }, []);
    
      return (
        <div className="environment">
          <p>The temperature is {temperature}&#176; Celcius.</p>
        </div>
      );
    };
    
    

    useEffect() 具有空依赖项 [] 数组的行为与 componentDidMount 一样,它只运行一次。即在第一次加载时调用您的getTemperature

    之后,setState() 将保持温度值更新,并在温度更新时重新渲染组件。

    【讨论】:

      猜你喜欢
      • 2016-07-24
      • 1970-01-01
      • 2018-10-25
      • 2018-08-24
      • 1970-01-01
      • 2017-03-22
      • 1970-01-01
      • 2022-11-04
      • 1970-01-01
      相关资源
      最近更新 更多