首页 > 解决方案 > 如何诉诸递归数组(有孩子的数组)

问题描述

我正在尝试创建一个拖放组件,您可以在其中拖放每个组件以重新排序它们。

例如,考虑以下数组

const myData = [
  { id: 0, text: "test one" },
  { id: 1, text: "test tow" },
  { id: 2, text: "test three" },
  {
    id: 3,
    text: "main",
    sub: [
      { id: 4, text: "sub 1" },
      { id: 5, text: "sub 2" },
    ],
  },
];

如果用户将带有文本的元素(组件)拖放到元素"test one"下, { id: 4, text: "sub 1" }, 我想再次重新排序数据,如下所示

const myData = [
  { id: 1, text: "test tow" },
  { id: 2, text: "test three" },
  {
    id: 3,
    text: "main",
    sub: [
      { id: 4, text: "sub 1" },
      { id: 0, text: "test one" },
      { id: 5, text: "sub 2" },
    ],
  },
];

这是呈现数据的组件。

import Draggable from "../Hooks/Draggable";

function TreeItems(state) {
  const [state, dispatch] = useReducer(reducer, myData);
    return state.map((item, index) => (
      <TreeItem
        key={index}
        nodeId={`${index}`}
        label={
          <div draggable={true} {...Draggable(item, index, Update)}>
            {item.text}
          </div>
        }
      >
        {item.sub && TreeItems(item.sub)}
      </TreeItem>
    ));
  }

我试图删除拖动的元素,然后将其再次添加到发生放置事件的子数组或父数组中。


function deleting(state, action) {
  state.forEach((item) => {
    if (item.id === action.i.item.id) {
      state.splice(action.i.index, 1);
    } else if (item.sub) {
      deleting(item.sub, action);
    }
  });
  return state;
}
function adding(state, action) {
  state.forEach((item) => {
    if (item.id === action.item.id) {
      state.push(action.i.item);
      //max call stack size.
    } else if (item.sub) {
      adding(item.sub, action);
    }
  });
  return state;
}
function reordering(state, action) {
  // const { type, i, f, p } = action;
  const newState = deleting(state, action);
  const newState2 = adding(newState, action);
  return newState2;
}
function reducer(state, action) {
  switch (action.type) {
    case ACTIONS.REORDER:
      const newState = reordering(state, action);
      return [...newState];
    case ACTIONS.SUB:
      return state;
    case ACTIONS.UPSATETEXT:
      return state;
    default:
      console.log("none");
  }
}

但我遇到了类似的错误

执行的最大通话次数

而且我以太多方式更改代码删除功能工作得很好但是添加功能会导致诸如最大调用之类的错误,或者我记得我以某种方式更改了它并且它复制了拖放元素而不是删除添加然后添加它。

代码沙盒代码

标签: javascriptreactjsrecursion

解决方案


推荐阅读