All files / src/form/fields Ratings.tsx

9.52% Statements 2/21
0% Branches 0/9
0% Functions 0/5
9.52% Lines 2/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58                      66x             66x                                                                              
import React, { ReactElement, useEffect, useState } from 'react';
import { ColumnType, RecordProps } from '@props/RecordProps';
import { fetchCurrentValue } from '@utils/FetchUtils';
import { isNumber } from 'lodash';
import { Rate, Spin } from 'antd';
 
export interface RatingsProps  {
    value: RecordProps;
    type: ColumnType;
}
 
const translates: {[propName: string]: string} = {
    "modifyRatio": "修改率",
    "usageRatio": "使用率",
    "overallScore": "综合评分",
};
 
// 备注: 后台要将 API 返回的数值转换为 0 - 5 的一个数值,用以显示为 rating
const Ratings = (props: RatingsProps): ReactElement => {
    const { value, type} = props;
    const { id } = value;
    const [currentValue, setCurrentValue] = useState<RecordProps>();
    const [loading, setLoading] = useState<boolean>(true);
 
    useEffect(() => {
        fetchCurrentValue(type, id).then(value => {
            setCurrentValue(value);
        }).catch((e) => {
            console.error('fetch current value error', e);
        }).finally(() => {
            setLoading(false);
        });
    }, [type, id]);
 
    const ratings: Array<ReactElement> = [];
    for (const key in currentValue) {
        if(key === "id") {
            continue;
        }
        const value = currentValue[key];
        const trans = translates[key];
        // 暂时只支持 translates 列表中的字段显示
        if(value != null && isNumber(value) && trans != null) {
            // 接口返回的数值为 0 - 5 的一个数值,乘 20 以得到 0 - 100 的数值(百分比)
            const percent = value * 20;
            ratings.push(
                <span key={key}>
                  <span className="ant-rate-text">{trans}: {percent}%</span>
                  <Rate value={value} disabled={true} allowHalf={true} />
                </span>
            );
        }
    }
    return loading? <Spin /> : (<>{ratings}</>);
};
 
export default Ratings;