繁体   English   中英

我应该怎么做才能从 API 调用中呈现数组对象值的总和

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM