我只有一個首先獲取設備串列的功能。該串列是一個 JSON 陣列。然后該函式回圈遍歷每個元素并請求陰影。
該函式使用設備屬性和陰影屬性構建一個新陣列
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>
);
}
```
uj5u.com熱心網友回復:
如果此處不使用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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/487206.html
標籤:javascript 节点.js 反应 json 亚马逊网络服务
