react+antd 遞歸實現(xiàn)樹狀目錄操作
1.寫在前面
作為前端小白的我一直對算法和數(shù)據(jù)結(jié)構(gòu)淺嘗輒止,噥,吃虧了。使用多次遞歸實現(xiàn)數(shù)據(jù)格式化后將數(shù)據(jù)進行樹狀展示的目的,分享一下我這次撓頭的經(jīng)歷~
2.數(shù)據(jù)
后臺傳過來的數(shù)據(jù)大概是這樣的
{
"data":[
{
"id":1,
"name":"一級節(jié)點",
"parentId":0,
"isValid":true,
"canAddChild":true,
"parent":null,
"children":[]
},{
"id":3,
"name":"二級節(jié)點",
"parentId":1,
"isValid":true,
"canAddChild":true,
"parent":null,
"children":[]
}
],
"status":1
}
3.數(shù)據(jù)格式
data里面每個元素的parentId指向是父級元素的id,parentId為0的是結(jié)構(gòu)樹的頂級元素,但現(xiàn)在是個平面的數(shù)組不好處理,而我們要做的是樹狀的結(jié)構(gòu),所以首先要對數(shù)據(jù)進行格式化,將一個元素的所有子元素放到該元素的children屬性中去。那么,遞歸就來了。
createTree = data => {
let treeArr = [];
//獲取頂級父元素集合
let roots = data.filter(elemt => elemt.parentId === 0);
treeArr.push(...roots);
//從頂級元素開始,獲取每個元素的子元素放到該元素的children屬性中
const getChildren = (resultarr,data) => {
resultarr.forEach((elemt,index) => {
elemt.children = data.filter((item,index) => item.parentId === elemt.id);
//判斷當前元素是不是有子元素被添加,如果有,再在子元素這一層循環(huán)
if(elemt.children.length > 0){
getChildren(elemt.children,data);
}
});
}
getChildren(treeArr,data);
//最后更新一下數(shù)據(jù)
this.setState({
treeArr
})
4.組件格式
因為UI組件用的是antd,使用Tree和TreeNode做樹結(jié)構(gòu)。因為數(shù)據(jù)已經(jīng)是樹狀的了,而且深度我們不確定,想要按層級輸出UI控件,那么,遞歸又來了。
renderTree = jsonTree => jsonTree.map( value => {
//遍歷樹狀數(shù)組,如果發(fā)現(xiàn)他有children則先套上<TreeNode>,再對他children中的元素做相同的操縱,直到children為空的元素停止,說明他們已經(jīng)是最深的那一層了。
if(value.children){
return(
<TreeNode title={
<span>
{value.name}
<Icon type="plus" onClick={this.showModal.bind(this,2,value.id)} />
<Icon type="edit" onClick={this.showModal.bind(this,1,value.id)} />
<Icon type="delete" onClick={this.showModal.bind(this,0,value.id)} />
</span>
} key={value.id}>
//對children中的每個元素進行遞歸
{this.renderTree(value.children)}
</TreeNode>
)
}
})
至此,就基本完成對數(shù)據(jù)的格式和對UI樹的格式啦,最后在樹控件中調(diào)用它,OK~
5.瘋狂輸出
render(){
return(
<Tree showLine={true}>
{this.renderTree(this.state.treeArr)}
</Tree>
)
}
運行,Bingo~
tips
因為目錄樹的每一項都是可編輯的,而原始的UI組件也沒有可用配置,后來查閱文檔竟然應該在TreeNode的title樹形中添加樹的自定義元素,可以,很強勢,官方文檔,看就完了,哈哈。
補充知識:antd的tree樹形組件異步加載數(shù)據(jù)小案例
前不久,做業(yè)務需求時遇到一個樹形選擇的 問題 , 子節(jié)點的數(shù)據(jù)要通過點擊展開才去加載,在antd給出的官方文檔中也有關于動態(tài)加載數(shù)據(jù)的demo,然而不夠詳細,自己研究之后,整理出來共享給大家借鑒下。
view.jsx(純函數(shù)式聲明)
// 渲染樹的方法
const loop = data => data.map((item) => {
const index = item.regionName.indexOf(modelObj.searchValue);
const beforeStr = item.regionName.substr(0, index);
const afterStr = item.regionName.substr(index + modelObj.searchValue.length);
const title = index > -1 ? (
<span>
{beforeStr}
<span style={{ color: '#f50' }}>{modelObj.searchValue}</span>
{afterStr}
</span>
) : <span>{item.regionName}</span>;
if (item.children && item.children.length > 0) {
return (
<TreeNode key={item.regionCode} parentId={item.parentId} title={getTreeTitle(title, item)}>
{loop(item.children)}
</TreeNode>
);
}
return <TreeNode key={item.regionCode} parentId={item.parentId} title={getTreeTitle(title, item)} isGetDealer={item.isGetDealer} isLeaf={item.isLeaf}/>;
});
//樹結(jié)構(gòu)展開觸發(fā)的方法
const onExpand = (expandedKeys) => {
console.log('onExpand-->', expandedKeys);
dispatch({
type: `${namespace}/onExpand`,
payload: {
expandedKeys,
autoExpandParent: false,
}
});
}
//異步加載樹形結(jié)構(gòu)子節(jié)點的方法
const onLoadData = (treeNode) => {
return new Promise((resolve) => {
resolve();
if(treeNode.props.isGetDealer===1){
let cityIds =treeNode.props.eventKey;
dispatch({
type: `${namespace}/queryDealers`,
payload: {
checkedKeys:cityIds,
}
});
}
})
}
//節(jié)點被選中時觸發(fā)的方法
const onCheck = (checkedKeys,e) => {
console.log('checkedKeys',checkedKeys);
if(checkedKeys.length > 0) {
updateModel(checkedKeys,'checkedKeys');
} else {
updateModel([], 'sellers');
updateModel([], 'checkedKeys');
}
}
//dom渲染
return (
{/* 經(jīng)銷商省市選擇 */}
{
modelObj.designatSeller === 1 && <div style={{marginBottom:20}}>
<div className = {styles.treeStyle} style={{ backgroundColor: '#FBFBFB', width: 343, paddingLeft: 8, height: 200, overflow: 'auto' }}>
<Tree
checkable
onExpand={onExpand}
expandedKeys={modelObj.expandedKeys}
checkedKeys={modelObj.checkedKeys}
//checkStrictly={true}
autoExpandParent={modelObj.autoExpandParent}
onCheck={onCheck}
loadData={onLoadData}
>
{loop(modelObj.countryList)}
</Tree>
</div>
</div>
}
)
mod.js
//初始默認狀態(tài)
const defaultState = {
countryList:[], //省市樹
expandedKeys: [], //樹數(shù)據(jù)
autoExpandParent: true,
checkedKeys:[],//當前選中的節(jié)點
}
// 方法列表
effects: {
//根據(jù)城市獲取經(jīng)銷商
*queryDealers({payload}, { call, put, select }) {
let {countryList} = yield select(e => e[tmpModule.namespace]);
let {data, resultCode } = yield call(queryDealers, {cityCodes:payload.checkedKeys});
if(resultCode === 0 && data.length > 0) {
let sellers = data.map(x=>x.dealerId);
yield put({
type: 'store',
payload: {
sellers
}
});
let gdata = groupBy(data, 'cityCode');
setgData(countryList);
yield put({
type: 'store',
payload: {countryList }
});
function setgData(arr) {
if(arr&&arr.length>0){
arr.forEach(x=>{
if(x.regionCode.split(',')[1] in gdata) {
x.children = gdata[x.regionCode.split(',')[1]].map(x=>{
return {
children:[],
regionName:x.dealerName,
regionCode:x.provinceCode+','+x.cityCode+','+x.dealerId,
regionId:x.dealerId,
isLeaf:true
};
})
} else {
setgData(x.children);
}
})
}
}
}
},
//獲取省市樹
*queryCountry({ }, { call, put, select }) {
let { countryList,biz} = yield select(e => e[tmpModule.namespace]);
let resp = yield call(queryCountry);
// console.log('resp_country-->',resp)
if(resp.resultCode === 0){
let dataList = cloneDeep(countryList);
dataList = [{
children: resp.data,
regionName:'全國',
regionId:'100000',
regionCode:'100000'}];
dataList.map((one,first)=> {
one.children.map((two,second)=> {
two.children.map((three,third)=> {
three.children.map((four,fouth)=>{
four.regionCode = three.regionCode+','+four.regionCode;
//是否為最后的子節(jié)點去獲取經(jīng)銷商
four.isGetDealer=1;
four.children = [];
})
})
})
})
yield put({
type: 'store',
payload: {countryList: dataList }
});
}
},
//展開節(jié)點觸發(fā)
*onExpand({ payload }, { call, put, select }){
yield put({
type: 'store',
payload: {
expandedKeys:payload.expandedKeys,
autoExpandParent:payload.autoExpandParent
}
});
},
}
回顯時后端需要返回的數(shù)據(jù)格式如下:
checkedKeys:[0:"500000,500100,2010093000863693"
1:"500000,500100,2010093000863790"]
說明: 這個例子只是貼出了一部分重要代碼,具體使用時需要補充完整。
以上這篇react+antd 遞歸實現(xiàn)樹狀目錄操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
React如何使用localStorage及實現(xiàn)刪除筆記操作過程
這篇文章主要介紹了React如何使用localStorage及實現(xiàn)刪除筆記操作過程,本文通過實例代碼給大家介紹的非常詳細,感興趣的朋友一起看看吧2024-12-12
React Hooks: useEffect()調(diào)用了兩次問題分析
這篇文章主要為大家介紹了React Hooks: useEffect()調(diào)用了兩次問題分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-11-11

