NemoZhong / blog-nemo

0 stars 0 forks source link

开发中遇到的问题,及解决方案 #6

Open NemoZhong opened 1 year ago

NemoZhong commented 1 year ago
NemoZhong commented 1 year ago
// 因为分隔符可以是任意的,字符串每段不能包含特殊字符,因此取巧地将所有特殊字符先替换为'%',split 之后再构造树结构
// 'abcdefg\*123.vvv'->'abcdefg%123%vvv'->['abcdefg','123','vvv']->tree

let treeList =[ ...data ];
// 点位名称不能是% 所有用%占位分割
const specialChar = '%';

const list = treeList
  ?.map(item => {
    let str = item.name;
    currentDataSource.nodeSeparatorList.forEach(
      rule => (str = str.replaceAll(rule, specialChar)),
    );
    return str;
  })
  .map(tempStr => tempStr.split(specialChar));

// 构造树数据  key为id 拼%+index, 到时候调接口时,按%去截取就可以了
treeList = list.map((ary, index) => {
  const { id, ...restProps } = treeList[index];
  return convertTree(
    ary,
    treeList[index]?.id,
    { ...restProps, rootId: currentDataSource.id },
    index,
  );
});

// 传 [a,b]  =>  [{key:a,children:[{key:b}]}]
// 根据树节点分割树
const convertTree = (list, id, restProps, count) => {
  if (!id) return;
  const rootName = list[0] || '--';
  const rest = list.splice(1);
  const key = id + '%' + count + 1;

  if (rest.length === 0) {
    return {
      key,
      id: key,
      ...restProps,
      isLastNode: true,
      name: rootName,
    };
  }
  return {
    key,
    id: key,
    ...restProps,
    name: rootName || '--',
    children: [convertTree(rest, id, restProps, count + 1)],
  };
};
NemoZhong commented 1 year ago
NemoZhong commented 1 year ago
    _rankList.sort((a, b) => compare(a, b, 'averagePrice', 'averageFloatPrice'))

    let rank = 0
    const rankAry = []
    _rankList.reduce((prev, cur) => {
      if (
        prev.averagePrice !== cur.averagePrice ||
        prev.averageFloatPrice !== cur.averageFloatPrice
      ) {
        rank++
      }
      rankAry.push(rank)
      return cur
    }, {} as any)

    setRankList(
      _rankList.map((item, index) => ({
        ...item,
        rank: rankAry[index],
      }))
    )

export const compare = (a, b, key1, key2) =>
  a[key1] - b[key1] || a[key2] - b[key2] || 0
NemoZhong commented 1 year ago
NemoZhong commented 1 year ago
 export const compare = (
    a: object,
    b: object,
    sortKeysAry: { key: String, type: 'asc' | 'desc' }
  ) => {
    let res
    sortKeysAry.forEach(({ type, key }) => {
      res = res || type === 'asc' ? a[key] - b[key] : b[key] - a[key]
    })
    return res || 0
  }
NemoZhong commented 1 year ago
NemoZhong commented 1 year ago

服务端没有localstorage,上述方案只兼容了客户端的逻辑,服务端取不到localstorage,会报警告text content did not match. server: "xxx" client: "aaa"

解决方案:store里初始值不要去localstorage去取,useEffect初始化时,js去取storage里的数据手动赋值

NemoZhong commented 1 year ago
NemoZhong commented 1 year ago