关于地区联动
import {useState, useEffect} from 'react';
import {getRegionOne, getRegionTwo} from '@/constants/actions';
import {regionSlice} from '@/store/region';
import store from '@/store/index';
const {saveRegion} = regionSlice.actions;
const deepChildren = (list: any) => {
return list.map((item: any) => {
let children: Region[] = [];
if (Array.isArray(item?.child) && item.child.length > 0) {
children = deepChildren(item.child);
}
return {
value: item.adminDivisionCd,
label: item.adminDivisionCnNm,
children,
};
});
};
export interface Region {
value: string;
label: string;
children?: Region[];
}
const useRegion = () => {
const [changePromise, setChangePromise] = useState<Region[]>([]);
useEffect(() => {
(async () => {
const result = await getRegionOne();
const newList = result.map(async (item: any) => {
const copyItem = item;
copyItem.value = item.adminDivisionCd;
copyItem.label = item.adminDivisionCnNm;
const res = await getRegionTwo({parentCd: item.value});
copyItem.children = deepChildren(res);
return {
value: copyItem.value,
label: copyItem.label,
children: copyItem.children,
};
});
Promise.all(newList).then(res => {
console.warn('Promise.all(newList).then', res);
setChangePromise(res);
store.dispatch(
saveRegion({
region: res,
})
);
});
})();
}, []);
return {
region: changePromise,
};
};
export default useRegion;
const reverseStr = (str: string, region?: any) => {
const findArr: string[] = [];
if (str.constructor === String) {
const casterList = str
.split(',')
.map(item => {
if (item[0]) {
return item.split('-');
}
return ['', ''];
})
.filter(ele => ele);
const deepFind = (list: any, findCode: string, curItem?: any) => {
list.forEach((item: any) => {
if (item.value === findCode) {
const addItem = curItem?.value || '';
findArr.unshift(addItem);
deepFind(region, addItem);
}
if (!(item.value === findCode)) {
deepFind(item.children, findCode, item);
}
});
};
const code = casterList[0][0];
deepFind(region, code);
const newArr = casterList.map((item: string[]) => {
return findArr.filter(ele => ele).concat(item);
});
return newArr;
}
};
export default reverseStr;