【问题标题】:Reactjs code works without error but executes twiceReactjs 代码可以正常工作但执行两次
【发布时间】:2022-01-07 17:01:05
【问题描述】:

使用 aws sdk for iot 我正在尝试在 aws iot 核心平台上制作一个东西并创建一个证书。下面是我用来执行这些操作的完整代码。

import {
  IoTClient,
  CreateThingCommand,
  CreateKeysAndCertificateCommand,
} from "@aws-sdk/client-iot";

const Demo = () => {
  var config = {
    region: "us-east-1",
    credentials: {
      accessKeyId: "XXXXXXX",
      secretAccessKey: "XXXXXXX",
    },
  };
  const client = new IoTClient(config);
  (async () => {
    const thingRequest = new CreateThingCommand({
      thingName: "demo-thing-name-using-sdk",
    });
    const certificateRequest = new CreateKeysAndCertificateCommand({setAsActive : true});
    try {
      const thingCreated = await client.send(thingRequest);
      const cert = await client.send(certificateRequest);
      let thingArn = thingCreated.thingArn;
      console.log(cert);
      console.log(thingCreated);
    } catch (error) {
      console.error(error);
    }
  })();
  return null;
};
export default Demo;

上述代码在 aws iot 核心控制台中执行并创建了两次事物和证书。请帮我解决问题

【问题讨论】:

  • 你在哪里/如何调用函数?如果它在 useEffect 中,可能是由 react 中的多个渲染引起的,请通过添加一个空的依赖数组来解决此问题。例如:useEffect(()=>{/*Run code here*/},[]) 这个 useEffect 只会在组件挂载时运行。
  • 非常感谢@AlvinCHENG
  • 请阅读this,了解如何在客户端应用程序中提供凭据。如果您将凭证向 AWS 公开给客户端,那就不好了

标签: reactjs amazon-web-services iot aws-iot


【解决方案1】:

useEffect 中输入您的代码以仅运行一次

import React, {  useEffect } from 'react';

然后在你的函数中

useEffect(()=>{
  //enter here your code
},[])

【讨论】:

    猜你喜欢
    • 2019-04-11
    • 1970-01-01
    • 2011-08-29
    • 1970-01-01
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-28
    相关资源
    最近更新 更多