javascript - 显示来自 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'));
解决方案
有多种方法可以实现这一点,但您需要有效地循环数据数组并累积/添加 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}
推荐阅读
- react-native - 在生产模式下反应原生 iOS 应用程序崩溃
- python - 如何从 twitch 聊天中获取最近的消息?
- wso2 - 使用 WSO2 作为 docebo 系统的身份提供者
- python - 更改括号类型更改返回类型
- python-3.x - 如何将 tf.estimator 转换为 keras 模型?
- java - 如何最大化和最小化 Swing 中 JPanel 内的 JTable?
- python-3.x - 如何将csv文件从s3复制到mysql rds
- asp.net-core - Razor Pages - 不使用 post 运行服务器端方法
- drools - 规则引擎是否适合根据一组规则验证数据?
- kubernetes - Kubernetes 中的列表类型标签