问题:项目中在开发的时候用到react-json-view 但是项目中发现 当数值类型超过 16为的时候就会出现精度问题
12112323123132131213    //后台返回的数据
12112323123132130000   //前台展示的时候就会变成这样,超过16位的多出的就会变成0
解决问题:
import ReactJson from 'react-json-view'
import BigNumber from 'bignumber.js';
import JSONBig from 'json-bigint';
import _ from 'lodash';
//这个方法通过递归会把所有的把sonBig改成字符串  
const handleJsonBig = json => {
        if (_.isArray(json)) {
          _.forIn(json, (value, index) => {
            if (BigNumber.isBigNumber(json[index])) {
              json[index] = json[index].toString();
            } else {
              json[index] = handleJsonBig(json[index]);
            }
          });
        } else if (_.isPlainObject(json)) {
          _.forIn(json, (value, key) => {
            if (BigNumber.isBigNumber(json[key])) {
              json[key] = json[key].toString();
            } else {
              json[key] = handleJsonBig(json[key]);
            }
          });
        }
        return json;
      };
      
      useEffect(()=> {
      //react-json-view它的src的数据需要的是一个有原型链的数据 所有通过 _.cloneDeep 深拷贝 details.reqObj这个数据 再通过handleJsonBig()方法把JSONBig数据 改成字符串 从而实现了js丢失精度的问题 
          setReqJson(details.reqObj ? handleJsonBig(_.cloneDeep(JSONBig.parse(details.reqObj))) : {})
      }, [details])
return (
	<>
	{isJSONReq() ? <div style={{overflow:'auto',backgroundColor:'rgb(29, 31, 33)'}}><ReactJson theme="google"  src={reqJson} collapseStringsAfterLength={10} enableClipboard={false} displayDataTypes={false} /></div> : <div style={{overflow:'auto',backgroundColor:'rgb(29, 31, 33)'}}>{details.reqObj}</div>}
	</>
)
贴下所有完整代码
import React, { useEffect, useState } from 'react';
import { getInterfaceLog } from '@/services/logService/logService';
import F from '@/utils/locale';
import { Modal, Button, Card, Descriptions } from 'antd';
import ReactJson from 'react-json-view'
import BigNumber from 'bignumber.js';
import JSONBig from 'json-bigint';
import _ from 'lodash';
interface IDetails {
    visible: boolean,
    onCancel: any,
    id: string
}
const Details: React.FC<IDetails> = (props) => {
    const { visible, onCancel, id } = props
    const [details, setDetails]: any = useState({})
    const [reqJson, setReqJson] = useState({})
    const [resJson, setResJson] = useState({})
    useEffect(() => {
        if (id) {
            getInterfaceLog({ id }).then(res => {
                if (res.code === '0') {
                    setDetails(res.data)
                }
            })
        }
    }, [onCancel])
    const isJSON = function () {
        try {
            JSON.parse(details.respObj);
        } catch (e) {
            return false;//转化失败捕捉错误返回false
        }
        return true;//转换成功则返回true
    }
    const isJSONReq = function () {
        try {
            JSON.parse(details.reqObj);
        } catch (e) {
            return false;//转化失败捕捉错误返回false
        }
        return true;//转换成功则返回true
    }
    const handleJsonBig = json => {
        if (_.isArray(json)) {
          _.forIn(json, (value, index) => {
            if (BigNumber.isBigNumber(json[index])) {
              json[index] = json[index].toString();
            } else {
              json[index] = handleJsonBig(json[index]);
            }
          });
        } else if (_.isPlainObject(json)) {
          _.forIn(json, (value, key) => {
            if (BigNumber.isBigNumber(json[key])) {
              json[key] = json[key].toString();
            } else {
              json[key] = handleJsonBig(json[key]);
            }
          });
        }
        return json;
      };

      useEffect(()=> {
          setReqJson(details.reqObj ? handleJsonBig(_.cloneDeep(JSONBig.parse(details.reqObj))) : {})
          setResJson(details.respObj ? handleJsonBig(_.cloneDeep(JSONBig.parse(details.respObj))) : {})
      }, [details])
   
    return (
        <>
            <Modal
                title={F({ id: 'rp.Interface.interaction.log.details' })}
                visible={visible}
                onCancel={onCancel}
                width={1000}
                maskClosable={false}
                footer={[
                    <Button onClick={onCancel}>
                        {F({ id: 'rp.cancel' })}
                    </Button>
                ]}
            >
                {/* "RP信息" */}
                <Card
                    title={F({ id: 'rp.Interface.Interaction.Logs' })}
                    extra={<div />}
                    style={{ width: '100%', fontSize: '16px' }}
                >
                    <Descriptions column={2}>
                        <Descriptions.Item label={F({ id: 'logManagement.docking.system' })}>{details.sys}</Descriptions.Item>
                        <Descriptions.Item label={F({ id: 'logManagement.the.name.of.the.interface' })}>
                            {details.interfaceName}
                        </Descriptions.Item>
                        <Descriptions.Item label={F({ id: 'logManagement.the.data.flow' })}>
                            {details.fromTo}
                        </Descriptions.Item>
                        <Descriptions.Item label={F({ id: 'logManagement.time.of.occurrence' })}>{details.createTime}</Descriptions.Item>
                        <Descriptions.Item label={F({ id: 'logManagement.operation.result' })}>
                            {details.result === 1 ? F({ id: 'logManagement.success' }) : F({ id: 'logManagement.fail' })}
                        </Descriptions.Item>
                    </Descriptions>
                </Card>
                <Card
                    title={F({ id: 'rp.Interface.request.data' })}
                    extra={<div />}
                    style={{ width: '100%', fontSize: '16px' }}
                >
                    {isJSONReq() ? <div style={{overflow:'auto',backgroundColor:'rgb(29, 31, 33)'}}><ReactJson theme="google"  src={reqJson} collapseStringsAfterLength={10} enableClipboard={false} displayDataTypes={false} /></div> : <div style={{overflow:'auto',backgroundColor:'rgb(29, 31, 33)'}}>{details.reqObj}</div>}
                </Card>
                <Card
                    title={F({ id: 'rp.Interface.response.data' })}
                    extra={<div />}
                    style={{ width: '100%', fontSize: '16px' }}
                >
                    {isJSON() ? <div style={{overflow:'auto',backgroundColor:'rgb(29, 31, 33)'}}><ReactJson  theme="google"  src={resJson} collapseStringsAfterLength={10} enableClipboard={false} displayDataTypes={false} /></div> : <div style={{overflow:'auto',backgroundColor:'rgb(29, 31, 33)'}}>{details.respObj}</div>}
                </Card>
            </Modal>
        </>
    );
};
export default Details
总结:react-json-view它的src的数据需要的是一个有原型链的数据 所有通过 _.cloneDeep 深拷贝 details.reqObj这个数据 再通过handleJsonBig()方法把JSONBig数据 改成字符串 从而实现了js丢失精度的问题

希望可以帮助你

Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐