REACT组件呈现,然后消失



我只有一个函数首先获得设备列表。列表是一个JSON数组。然后该函数循环遍历每个元素并请求阴影。

函数使用device属性和shadow属性构建一个新的数组

REACT页面呈现并显示数据一秒钟,然后消失。

如果我修改getShadow函数,让它只返回设备列表(不带阴影),页面就会呈现得很好。但是,当我使用来自每个设备的阴影数据构建新数组时,问题就开始了。

你知道我在这里错过了什么吗?

多谢

代码

async function getShadows() { 
const listThings_command = new ListThingsCommand({});
const data = await iotClient.send(listThings_command);  /* First get the list of things */ 
const things = data.things;
let devices_list = [];  // to store the final array with data to render
let shadowRequests = things.map (thing => {   /* List calls to get shadow for each thing */ 
return new Promise((resolve, reject) => {
const getThingShadow_command = new GetThingShadowCommand({thingName: thing.thingName}); /** get device shadow */ 
iotDataPlaneClient.send(getThingShadow_command).then(
(data) => {
const string_data = new TextDecoder('utf-8').decode(data.payload);  /* Decode payload as it is returned in Uint8Array format*/ 
const shadow_data = JSON.parse(string_data);
var deviceInfo = {  /* Create a new object to store required device info*/ 
thingName : thing.thingName,
thingTypeName: thing.thingTypeName,
thingArn : thing.thingArn,
shadow : shadow_data.state.reported
};
resolve(deviceInfo);
},
(error) => {
reject(error);
}
); 
})
})
Promise.all(shadowRequests).then((data) => {
data.forEach (res => {  /* loop over each promise */ 
if (res) {
devices_list.push(res); /* add the data as a new element in the array*/ 
}
})
}
)
return devices_list;
}; 

function Home (){
const [mydevices, updateMydevices] = React.useState([]);
useEffect(() => {
getShadows().then(data => updateMydevices(data)); 
}, []);    

return (
<div className="App">
<h1>Dashboard</h1> 
<div>
<h4>Devices List</h4>
<ListGroup id="device_list">
{
mydevices.map((device, key) => {
return (
<ListGroup.Item key = {key}> 
<div>{device.thingName} </div>
</ListGroup.Item>
)
})
}
</ListGroup>
</div> 
</div>
);
}
```

如果这里不使用await,则设备列表将在影子请求完成之前返回。所以它总是一个空数组。你可以试试这样做。

try {
const data = await Promise.all(shadowRequests);
data.forEach (res => {  /* loop over each promise */ 
if (res) {
devices_list.push(res); /* add the data as a new element in the array*/ 
}
})
}
catch(err) {
//handle error
}
return devices_list;

最新更新