【发布时间】:2019-01-08 18:14:59
【问题描述】:
我必须执行多个提取查询。根据我的第一个查询,我在收到所有我应该能够将数据分配给反应组件状态后进行多个其他查询。看来我在 fetch 方法完成之前将值分配给组件状态,因此它们显示为空数组。
我已经尝试移除外部的内部 fetch 方法并执行查询。
import React, { Component } from 'react';
import './App.css';
import Sensors from './iot/Sensors';
class App extends Component {
constructor (props) {
super (props);
this.state = {
status: 'disconnected',
devices: [],
dataPoints: []
};
}
componentDidMount() {
// Get Zigbee devices
fetch('http://localhost:3000/ssapi/zb/dev')
.then((res) => res.json())
.then((data) => {
this.setState({
devices : data
})
data.map((device) => {
const dataPoint = []
JSON.parse(device.metadata).dataGroups.map((datagroup) =>{
const url = 'http://localhost:3000/ssapi/zb/dev/' + device.id + '/ldev/' + datagroup.ldevKey + '/data/' + datagroup.dpKey;
fetch(url)
.then((res) => res.json())
.then((data) =>{
dataPoint.concat(data)
console.log('Data', data);
console.log('Inside dataPoint', dataPoint);
})
.catch((error) => console.log(error));
}) // dataGroups.map
console.log("Final dataPoint", dataPoint);
const dataPoints = this.state.dataPoints.concat(dataPoint);
this.setState({ dataPoints });
}) // data.map
}) // fetch
.catch((error) => console.log(error));
}
render() {
console.log('Render Devices', this.state.devices);
console.log('Render dataPoints', this.state.dataPoints);
}][1]][1]
我期待最终的组件状态看起来像这样 或在渲染功能中 - 控制台日志记录应如下所示。
devices = [{},{},{},{},{}...]
dataPoints = [[{},{},{},..], [{},{},{},..], [{},{},{},..], ....]
【问题讨论】:
标签: javascript reactjs fetch