欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

react+antd 遞歸實現(xiàn)樹狀目錄操作

 更新時間:2020年11月02日 09:50:36   作者:宋三步  
這篇文章主要介紹了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給出的官方文檔中也有關(guān)于動態(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)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • React-Hook中使用useEffect清除定時器的實現(xiàn)方法

    React-Hook中使用useEffect清除定時器的實現(xiàn)方法

    這篇文章主要介紹了React-Hook中useEffect詳解(使用useEffect清除定時器),主要介紹了useEffect的功能以及使用方法,還有如何使用他清除定時器,需要的朋友可以參考下
    2022-11-11
  • React使用高德地圖的實現(xiàn)示例(react-amap)

    React使用高德地圖的實現(xiàn)示例(react-amap)

    這篇文章主要介紹了React使用高德地圖的實現(xiàn)示例(react-amap),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-04-04
  • React Native 搭建開發(fā)環(huán)境的方法步驟

    React Native 搭建開發(fā)環(huán)境的方法步驟

    本篇文章主要介紹了React Native 搭建開發(fā)環(huán)境的方法步驟,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-10-10
  • react如何修改循環(huán)數(shù)組對象的數(shù)據(jù)

    react如何修改循環(huán)數(shù)組對象的數(shù)據(jù)

    這篇文章主要介紹了react如何修改循環(huán)數(shù)組對象的數(shù)據(jù)問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-12-12
  • react中如何使用定義數(shù)據(jù)并監(jiān)聽其值

    react中如何使用定義數(shù)據(jù)并監(jiān)聽其值

    這篇文章主要介紹了react中如何使用定義數(shù)據(jù)并監(jiān)聽其值問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2024-01-01
  • React tabIndex使非表單元素支持focus和blur事件

    React tabIndex使非表單元素支持focus和blur事件

    這篇文章主要為大家介紹了React使用tabIndex使非表單元素支持focus和blur事件實例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-11-11
  • ReactNative頁面跳轉(zhuǎn)Navigator實現(xiàn)的示例代碼

    ReactNative頁面跳轉(zhuǎn)Navigator實現(xiàn)的示例代碼

    本篇文章主要介紹了ReactNative頁面跳轉(zhuǎn)Navigator實現(xiàn)的示例代碼,具有一定的參考價值,有興趣的可以了解一下
    2017-08-08
  • React Native中WebView與html雙向通信遇到的坑

    React Native中WebView與html雙向通信遇到的坑

    這篇文章主要介紹了React Native中WebView與html雙向通信的一些問題,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習吧
    2023-01-01
  • React 原理詳解

    React 原理詳解

    這篇文章主要介紹了深入理解react的原理,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2021-10-10
  • react中的watch監(jiān)視屬性-useEffect介紹

    react中的watch監(jiān)視屬性-useEffect介紹

    這篇文章主要介紹了react中的watch監(jiān)視屬性-useEffect使用,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-09-09

最新評論