javascript - 挂载时计算父组件中多个子 React 组件的值的总和
问题描述
我目前正在学习 JS + ReactJS 并且有一个问题我自己无法解决。我有一个名为“AssetOverview”的父组件,它应该使用传递的资产对象(this.props.assetList)显示多个名为“Asset”的子组件。在每个资产组成部分中,都有一个起始值和一个预期利率。目前,我将当前金额与 20 年复合以获得未来金额。这最初是在我的子组件的构造函数中完成的,但我也有一个用于进一步计算的函数。
现在,我想在我的资产概览中显示所有资产组件的未来总金额。不幸的是,这不起作用。
import React from 'react';
import Asset from '../Asset/Asset';
class AssetOverview extends React.Component {
constructor(props) {
super(props);
this.state = {
total: 0
}
this.updateTotal = this.updateTotal.bind(this);
}
updateTotal(substract, add) {
const prevValue = this.state.total;
this.setState(
{ total: (prevValue - substract + add) }
);
}
render() {
return (
<div className="AssetOverview">
<h3>TOTAL: {(this.state.total).toFixed(0)}</h3>
<div className="AssetList">
{
this.props.assetList.map (asset => {
return <Asset asset={asset} updateTotal={this.updateTotal} />
})
}
</div>
</div>
)
}
}
export default AssetOverview;
另一个文件:
import React from 'react';
const years = 20;
class Asset extends React.Component {
constructor(props) {
super(props);
this.state = {
expectedInterestRate: this.props.asset.expectedInterestRate,
futureTotal: (this.props.asset.startingValue * Math.pow((1+ (this.props.asset.expectedInterestRate/100)),years))
};
this.compoundIt = this.compoundIt.bind(this);
this.props.updateTotal(0, this.state.futureTotal)
}
compoundIt(rate) {
const prevValue = this.state.futureTotal;
const newValue = this.props.asset.startingValue * Math.pow((1+ (rate/100)),years);
this.setState(
{ futureTotal: newValue }
)
this.props.updateTotal(prevValue, newValue);
}
render() {
return (
<div>
<tr>
<table className="asset-container">
<tr>
<td>Name: </td>
<td>{this.props.asset.name}</td>
</tr>
<tr>
<td>Start: </td>
<td>{this.props.asset.startingValue}</td>
</tr>
<tr>
<td>Zukunft: </td>
<td>{(this.state.futureTotal).toFixed(0)}</td>
</tr>
<tr>
<td>Zinsatz: </td>
<td>{(this.state.expectedInterestRate).toFixed(1)}</td>
</table>
</tr>
</div>
)
}
}
export default Asset;
从我到目前为止的尝试来看,在我看来,这只是一次。如果我有多个资产组件,它仍然可以工作 - 但只有一次。
我希望你能帮忙!
非常感谢,复活节快乐,注意安全。尼科
解决方案
推荐阅读
- java - 我的应用程序被智能管理器阻止。有什么解决办法吗?
- python-3.x - 使用 PIL 压缩图像而不改变图像的方向
- r - RStudio 更新后无法读取名称中带有西里尔符号的文件
- pdf - 从 PDF 文件复制时印地语内容失真
- amazon-web-services - ECS 集群中没有实例
- sql - 在同一查询中使用查询结果字段作为数据库名称
- tensorflow - Tensorflow dense_image_warp 无法转换类型的对象
张量 - django - 将数据添加到数据库后更新 Django 表单
- auth0 - Auth0 PasswordLess - 在锁定 11 中为用户提供电子邮件和短信验证选项
- .htaccess - Redirect all pages ( from a server to another's homepage) except one