我在componentDidMount()中调用了service中的Bootstrap-table呈现值。
我的表格示例 -
Col1 Col2 Col3
1 2 3
4 5 6
7 8 9
SumValue 15 18 //This last row holds sum of all values
如何计算col1中存在的所有值的SumValue并在页脚中显示。
下面是我如何使用react-row将数据映射到行的代码。 值是将设置为组件状态的json文件中存在的所有列的数据保存数据。
{this.state.value && this.state.value.map(function (value, ind) {
return <Row key={ind} item={value}></Row>
})
}
初始化状态
constructor(props){
super(props)
{
this.state ={
value: [], //Initializing an array
SumValue: '',
default: false,
}
}
设置状态
fetch('https://www.serviceUrl.com')
.then(res => res.json())
.then(value => {
this.setState({
value: value.empRecords, //Here its getting all records from json
default: false
});
})
如果需要更多信息,请告诉我们。
答案 0 :(得分:1)
我会使用 reduce
:
const SumValue = this.state.value&amp;&amp; this.state.value.reduce((a,v)=&gt; a + v,0)&#xA;
&#xA;
答案 1 :(得分:0)
1) initial columnNames and array list
state = {
callList: [],
columnModel: [
{ columnName: "date" },
{ columnName: "totalCalls" },
{ columnName: "answeredCalls" },
{ columnName: "abandonedCalls" },
{ columnName: "abandonRate" },
{ columnName: "avgAnswerSpeed" },
]
};
2) Get data from api and prepare array data
try {
const { errors, list, success } = (await apiService.getCalls(request)).data;
if (success) {
// first list is normal numbers count only,
// if you want count avg sum for some columns send second param array list and include column names
// now i want count avg for 'abandonRate', 'avgAnswerSpeed' , others just count sum
this.setState({
callList: list,
callListSum: this.sumCount(
list,
['abandonRate', 'avgAnswerSpeed']
)
})
}
} catch (error) {
console.log(error);
}
sumCount = (list = [], avgColumns = []) => {
const sum = {};
// count numbers
list.map((item) => {
Object.entries(item).map(([key, val]) => {
if (typeof (val) === 'number') {
sum[key] = sum[key] ? (sum[key] + val) : val;
}
})
});
// count avg
avgColumns.map(key => {
if (sum[key]) {
sum[key] = sum[key] / list.length;
}
})
return sum;
}
3) Render data
<table>
<thead>
<tr style={{ backgroundColor: "#F5F7FA" }}>
{
this.state.columnModel.map((item, i) =>
<th key={i}> {item.columnName}</th>
)
}
</tr>
</thead>
<tbody>
{
this.state.callList.map(
(info, index) => (
<tr
key={index}
>
{
this.state.columnModel.map((item, i) =>
(
<td key={i}>
{info[item.columnName]}
</td>
)
)
}
</tr>
)
)}
{/* Render sum area */}
<tr
style={{ backgroundColor: "#F5F7FA" }}
>
{
this.state.columnModel.map((item, i) =>
(
<td style={{ fontWeight: "bold" }} >
{this.state.callListSum[item.columnName]}
</td>
)
)
}
</tr>
</tbody>
</table>