ReactJs 计算表列中存在的所有值的总和



我有一个 Bootstrap-table 渲染来自 componentDidMount(( 中调用的服务的值。

我的表格示例 -

  Col1      Col2 Col3
   1         2    3
   4         5    6
   7         8    9
  SumValue  15   18 //This last row holds sum of all values

如何计算 col1 中存在的所有值的总和值并在页脚中显示的值。

下面是我如何使用 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
        });        
    })

如果需要更多信息,请告诉我。

我会使用 reduce 得到总和:

const SumValue = this.state.value && this.state.value.reduce((a, v) => a + v, 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>

相关内容

最新更新