【发布时间】:2018-04-18 20:57:43
【问题描述】:
我正在尝试使用对 JSON.server 的直接获取来检索基本包以加载一些简单的组件。当我在 Firefox 中运行这个脚本时。我在尝试获取资源时收到“网络错误”,但在网络连接本身中找不到任何 400 错误。我的问题是,什么会导致这种故障?因为页面的其余部分在调用时加载正常。
编辑1:明确说明data.StatusComponent未定义。
import React, { Component } from 'react';
import '../HeaderBar/HeaderBar.css';
import 'whatwg-fetch';
type StatusBarProps = {};
type StatusBarState = {
launch_timer: boolean;
foreGroundTimer: number;
// tslint:disable-next-line:no-any
statusBarBlocks: any;
};
class StatusBar extends Component<StatusBarProps, StatusBarState> {
timerId: number;
constructor() {
super();
this.state = {
launch_timer: true,
foreGroundTimer: -1,
statusBarBlocks: []
};
}
componentDidMount() {
fetch('http://localhost:5001/StatusComponent').then(results => {
return results.json();
}).then(data => {
let systemOff = 'green';
let systemOn = 'gray';
let statusBarBlocks = data.StatusComponent.map((Status) => {
return (
<div className="blockBar" id={Status.id} key={Status.key} style={{ backgroundColor: (this.state.foreGroundTimer >= Status.id) ? systemOff : systemOn }}> {Status.Name} </div>
);
});
this.setState({ statusBarBlocks: statusBarBlocks });
});
}
componentWillUnmount() {
clearInterval(this.timerId);
}
tick() {
this.setState({ launch_timer: !this.state.launch_timer, foreGroundTimer: (this.state.foreGroundTimer + 1) % 26 });
}
render() {
return (
<div className="location">
<div className="col-xs-6">
{this.state.statusBarBlocks}
</div>
</div>
);
}
}
export default StatusBar;
【问题讨论】:
-
在浏览器地址栏中输入
http://localhost:5001/StatusComponent。你看到回复了吗? -
@RickJolly 是的,它返回一个完整的 JSON 数组。这是通过 JSON 服务器发生的。
-
如果您是
console.log(data);,是否定义了data,它是否具有StatusComponent属性? -
promise 拒绝 fetch 的输出是什么?
-
@RickJolly 它正在返回一系列对象,所有这些对象都是正确的,但不是解析的对象数据。当我尝试在 let 语句下调用它时。它说 data.StatusComponent 是未定义的
标签: javascript reactjs fetch json-server