javascript - 如何诉诸递归数组(有孩子的数组)
问题描述
我正在尝试创建一个拖放组件,您可以在其中拖放每个组件以重新排序它们。
例如,考虑以下数组
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");
}
}
但我遇到了类似的错误
执行的最大通话次数
而且我以太多方式更改代码删除功能工作得很好但是添加功能会导致诸如最大调用之类的错误,或者我记得我以某种方式更改了它并且它复制了拖放元素而不是删除添加然后添加它。
- 请注意,沙盒说无法导入
material-ui
依赖项,我不知道为什么,但它在我的本地机器上运行良好。
解决方案
推荐阅读
- angular - Websocket CORS错误Angular
- php - PHP 将列数据添加到表中 IF 条件为真
- javascript - 将数组与对象属性匹配
- email - 通过 Mailchimp 向具有特定标签的新订阅者发送电子邮件
- python - ModuleNotFoundError:没有名为“poetry.console”的模块
- django - DevOps 和 Azure 应用服务中的环境变量
- asp.net-core-mvc - 创建新的 ASP.NET Core 5 MVC 项目后,所有视图上的 CS0234 错误
- swift - 如何检测盒子对象和球之间的碰撞
- python - 在 Tkinter 中移动时标签闪烁
- python - 如何检查两个值之间的数据框系列的每个范围是否有另一个值