![](/img/trans.png)
[英]My Javascript JSON code in HTML page does not render the RESTful API array objects, although I get the data from the API. What should I do?
[英]What should I do to render sum of array objects values from API call
在this.state.companiesIncome
,我有一个包含{value and date}
的 50 个对象的数组,但是当我尝试console.log(this.state.companiesIncome[2].value)
我收到TypeError: Cannot read property '2' of null
。 我做错了什么?
import React, { Component } from 'react'
import './CompanyTotalIncome.css'
import axios from 'axios'
class CompanyIncome extends Component {
constructor(props) {
super(props)
this.state = {
companyID: props.companyID,
companiesIncome: null
}
}
componentWillMount() {
axios.get(`https://API/${this.state.companyID}`).then(res => {
this.setState({ companiesIncome: res.data.incomes })
})
}
render() {
console.log(this.state.companiesIncome[2].value)
return (
<>
<th>Total income</th>
</>
)
}
}
export default CompanyIncome
componentWillMount
已被弃用。
使用componentDidMount
而不是componentWillMount
进行 AJAX 调用。
componentDidMount() {
axios.get(`https://API/${this.state.companyID}`).then(res => {
this.setState({ companiesIncome: res.data.incomes });
});
}
并在使用this.state.companiesIncome
之前进行this.state.companiesIncome
this.state.companiesIncome && console.log(this.state.companiesIncome[2].value);
您会在axios.get
触发本质上是异步的 AJAX 调用之前看到错误。 你的render
方法无论如何都会在componentDidMount
之前被调用。 所以当日志被调用时, this.state.companiesIncome
仍然是null
。
一旦componentDidMount
被调用,API 数据被获取并调用setState
,它将触发重新渲染并再次调用render
方法。 这次使用companiesData
集。 所以它会按预期工作。
这是您的参考的工作代码演示示例。
因为在初始状态您的公司收入为空,公司收入[2] 将抛出错误。 为避免这种情况,您可以执行以下操作:
this.state.companiesIncome && this.state.companiesIncome[2].value
这样,只有当您具有有效的公司收入值时才会打印它。 为了稍微改进它,您还可以编写:
(this.state.companiesIncome && this.state.companiesIncome.length >= 2) && this.state.companiesIncome[2].value
如果您只想将其记录到控制台,请执行以下操作:
console.log(this.state.companiesIncome ? this.state.companiesIncome[2].value : 'companiesIncome is null');
事实是 React 从一开始就开始渲染。 您可以查看JSFiddleExample ,在控制台中您将看到开头的渲染,然后是 componentDidMount。 因此,您必须添加验证。 this.state.companiesIncome! == null
this.state.companiesIncome! == null
。 当您更改 componentDidMount 中的状态时,渲染将再次使用您的数据开始。 你可以在React 文档中阅读 React Lifecycle
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.