【发布时间】:2018-07-18 09:22:24
【问题描述】:
我正在编写一个从 API 获取 JSON 数据并显示其中一些内容的 React 应用程序。
这是它得到的数据:
{"id":6,"name":"5 Storey I=0.7","Value":1344981250,"NSt":5,"jRatio":"[0.2,0.4,0.4]","jEDR":"[0.02,0.1,0.5,1]"}
这是应用程序:
class App extends React.Component{
constructor(props){
super(props);
this.state={
data: [],
isLoading: false,
error: null,
};
}
componentDidMount(){
this.setState({isLoading: true});
axios.get(API)
.then(response => console.log(response.data.Value))
.then(response => this.setState({data: response.data, isLoading: false}))
.catch(response => this.setState({error: response.error, isLoading: false}));
}
render(){
return (
<div>
<p>{this.state.error}</p>
<p>{this.state.isLoading ? 'Loading...':'Loaded'}</p>
<ul>{this.state.data.Value.toString()}</ul>
</div>
)
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
我在控制台中得到值“1344981250”,但页面抛出此错误:
TypeError: this.state.data.Value 未定义
在控制台中:
开发服务器已断开连接。必要时刷新页面。
我也试过这个:
this.state.data.map(obj => <li key={obj.toString()}>{obj.toString()}</li>)
这一次没有任何错误,页面上没有任何显示。 (这个适用于对象数组,但当它只是一个对象时什么都不显示)
那么我错过了什么?
【问题讨论】:
-
我的猜测是,在您的第二个
.then(response中,response是未定义的,因为这就是console.log()“返回”的内容。
标签: javascript reactjs axios