首页 > 解决方案 > 显示来自 API 的 id 的总和值

问题描述

目标:
在文本“所有id值的总和为:”后显示所有id值的总和,
id值来自API数据。

问题:
我不知道怎么做,有可能吗?

信息:
我是 React JS 的新手

Stackblitz:
https ://stackblitz.com/edit/react-f7chuv ?

谢谢!


import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';

class App extends Component {
  constructor() {
    super();
    this.state = {
      name: 'React',
      data: null
    };
  }

  componentDidMount = () => {
    fetch('https://jsonplaceholder.typicode.com/users')
      .then(res => res.json())
      .then(data => {
        this.setState(prevState => ({
          ...prevState,
          data
        }));
      });
  };

  render() {
    return (
      <div>
        <p>Start editing to see some magic happen :)</p>
        <ul>
          {this.state.data &&
            this.state.data.map(user => (
              <li key={user.id} id={user.id}>
                {user.id}
              </li>
            ))}
        </ul>
        <div>
          Total sum of all id value is: 
        </div>
      </div>
    );
  }
}

render(<App />, document.getElementById('root'));

标签: javascriptreactjs

解决方案


有多种方法可以实现这一点,但您需要有效地循环数据数组并累积/添加 ID。您可以使用Array reduce执行此操作:

Total sum of all id value is: {this.state.data && this.state.data.reduce((acc, curr) => acc + curr.id, 0)}

另一种选择是在内部的第一行render()

let idSum = 0;
for (let i = 0; this.state.data && i < this.state.data.length; i++) {
    idSum += this.state.data[i].id;
}

然后你可以输出idSum

Total sum of all id value is: {idSum}

推荐阅读