javascript - 我应该如何更新JS中二维数组中节点的ID?
问题描述
嘿,我一直在开发一个程序,用户可以在 2D 数组中的任何索引值处添加或删除节点,但问题是,我只得到点击的元素索引而不是全部,所以我应该如何操作这个的 ID二维数组。
click = (row, col ) => {
console.log("click fun",row, col);
// alert(window.event.clientX)
IDIS = `${row}${col}`;
// IDIS = window.event.clientX*window.event.clientY;
console.log("row ,col ", row, col);
console.log("dontTriggerClick", dontTriggerClick);
if (dontTriggerClick) {
dontTriggerClick = false;
return;
}
var { logic } = this.props;
console.log("logic", this.props);
const { currentProgramGuide } = logic;
var todo = "current";
logic.insertState = false;
const { type } = drawing.board[row][col];
console.log("type", type);
if (type === "blank" || type === "hand" || type === "highlighted_hand")
todo = "blank";
if (todo === "current") {
logic.active = [row, col];
console.log("click current");
drawing = ProgramToDrawing(
logic.program,
logic.end,
logic.currentProgramGuide,
logic.active,
this.add,
logic.insertState,
this.insertNode,
this.deleteNode
);
var logicState = {};
// logicState['type'] = this.state.currentLogicScreen;
// logicState['state'] = logic;
console.log("NOW ZOOM 3", this.props);
// IDIS=Math.floor(Math.random()*10000000000000)
// idss.push(`${row}-${col}`);
// logic.ids=idss;
this.props.update(logic);
} else if (todo === "blank") {
console.log("clickfun blank");
console.log("[-1, -1]");
logic.active = [-1, -1];
// Uncomment the following line to auto-minimize bottomPanel on blank space click
// logic.bottomPanel = 'border';
drawing = ProgramToDrawing(
logic.program,
logic.end,
logic.currentProgramGuide,
logic.active,
this.add,
logic.insertState,
this.insertNode,
this.deleteNode
);
var logicState = {};
logicState["type"] = this.state.currentLogicScreen;
logicState["state"] = logic;
console.log("NOW ZOOM 4", this.props);
this.props.update(logic);
}
};
recurseAdd = (instructions, nesting, toPush) => {
console.log("i am recurseAdd");
console.log(
"instructions11 new ",
typeof instructions,
instructions,
nesting - 1,
toPush
);
if (instructions.length !== 0) {
if (nesting === 0) {
console.log("IF CONDIOTION recurseAdd");
instructions.push(toPush);
} else {
console.log("ELSE CONDIOTION recurseAdd");
this.recurseAdd(
instructions[instructions.length - 1].subprogram,
nesting - 1,
toPush
);
}
console.log(
"END recurseAdd",
instructions.length !== 0,
typeof instructions,
instructions,
nesting - 1,
toPush
);
}
};
add = (type) => {
console.log("add fun");
console.log("add fun type", type);
if (type == "repeat") {
this.setState({ readyForSimulation: type });
sessionStorage.setItem("programEnd", type);
}
if (dontTriggerClick) {
console.log("dontTriggerClick");
dontTriggerClick = false;
return;
}
var { logic } = this.props;
logic.active = [-1, -1];
console.log("ANKIT 222", type);
// console.log("logic.program new", logic.program, type)
if (
type === "end_variable" ||
type === "end_sensor" ||
type === "end_condition" ||
type === "end_if" ||
type === "end_loop" ||
type === "repeat"
)
logic.currentProgramGuide--;
else {
var toPush = { type: type, state: {} };
console.log("logic.program", logic.program);
console.log("logic.currentProgramGuide", logic.currentProgramGuide);
console.log("toPush", toPush);
if (
type === "variable" ||
type === "sensor" ||
type === "condition" ||
type === "loop"
)
toPush.subprogram = [];
this.recurseAdd(logic.program, logic.currentProgramGuide, toPush);
if (
type === "variable" ||
type === "sensor" ||
type === "condition" ||
type === "loop"
)
logic.currentProgramGuide++;
}
console.log("addfun, ");
console.log(
"addfun : logic.currentProgramGuide ",
logic.currentProgramGuide
);
console.log("addfun : logic.active, ", logic.active);
drawing = ProgramToDrawing(
logic.program,
logic.end,
logic.currentProgramGuide,
logic.active,
this.add
);
var logicState = {};
logicState["type"] = this.state.currentLogicScreen;
logicState["state"] = logic;
console.log("NOW ZOOM 5", this.props);
this.props.update(logic);
};
insertNode = (type) => {
// console.log("insertNode", drawing.activeParentRef[drawing.activeIndex]);
// for(let n = 0; n<drawing.activeParentRef.slice(drawing.activeIndex, drawing.activeParentRef.length).length; n++){
// drawing.activeParentRef[n].id= JSON.stringify(Number(drawing.activeParentRef[n].id) + 1)
// }
// console.log("new drawing.activeParentRef[i]type", type)
console.log("ANKIT 333", type);
num++;
var { logic } = this.props;
if (!logic.insertState){
logic.insertState = true;
} else {
logic.insertState = false;
var temp = drawing.activeParentRef[drawing.activeIndex];
var toPush = { type: type, state: {}, id: IDIS};
if (
type === "variable" ||
type === "condition" ||
type === "sensor" ||
type === "loop"
)
toPush.subprogram = [];
drawing.activeParentRef[drawing.activeIndex] = toPush;
for (
let i = drawing.activeIndex + 1;
i < drawing.activeParentRef.length;
i++
) {
var temp2 = drawing.activeParentRef[i];
drawing.activeParentRef[i] = temp;
temp = temp2;
}
if (temp) drawing.activeParentRef.push(temp);
logic.active = [-1, -1];
}
console.log("logic.program", logic.program);
drawing = ProgramToDrawing(
logic.program,
logic.end,
logic.currentProgramGuide,
logic.active,
this.add,
logic.insertState,
this.insertNode,
this.deleteNode
);
var logicState = {};
logicState["type"] = this.state.currentLogicScreen;
logicState["state"] = logic;
console.log("NOW ZOOM 6", this.props);
this.props.update(logic);
this.onUpdate()
};
deleteNode = () => {
console.log("deleteNode");
var { logic } = this.props;
if (
drawing.activeParentRef.length - 1 == drawing.activeIndex &&
(drawing.activeRef.type === "variable" ||
drawing.activeRef.type === "sensor" ||
drawing.activeRef.type === "condition" ||
drawing.activeRef.type === "loop")
) {
let currentProgramGuide = 0,
temp = logic.program;
while (
temp != drawing.activeParentRef &&
currentProgramGuide < logic.currentProgramGuide
) {
temp = temp[temp.length - 1].subprogram;
currentProgramGuide++;
}
if (currentProgramGuide < logic.currentProgramGuide)
logic.currentProgramGuide = currentProgramGuide;
}
// alert(drawing.activeIndex)
drawing.activeParentRef.splice(drawing.activeIndex, 1);
logic.active = [-1, -1];
console.log("deleteNode fun ");
drawing = ProgramToDrawing(
logic.program,
logic.end,
logic.currentProgramGuide,
logic.active,
this.add,
logic.insertState,
this.insertNode,
this.deleteNode
);
var logicState = {};
logicState["type"] = this.state.currentLogicScreen;
logicState["state"] = logic;
console.log("NOW ZOOM 7", this.props);
this.props.logicComponent(logic);
this.onUpdate()
console.log("777777777777",this.props.logic.program)
};
还原逻辑:
case 'LOGIC_SELECTION':
var { program, end, insertState, offset, scale, currentProgramGuide, active, bottomPanel } = payload
var data = { ...state, program, end, insertState, offset, scale, currentProgramGuide, active, bottomPanel }
// sessionStorage.setItem('logic', JSON.stringify(data));
return data;
我尝试了所有方法,但我在 2D 部分遇到问题意味着数组像第一行然后是第二行,但我想像流程图中的图表流一样打印它
解决方案
不确定您的数据结构是什么样的以及为什么发布看起来过于复杂的代码,如果您有问题,您应该发布一个最小的可重现示例。
所以我忽略了您的代码转储,因为 SO 不是调试代码的站点,如果您对代码设计有疑问,可以尝试代码审查。
以下是您的问题的答案示例:
我应该如何更新JS中二维数组中节点的ID?
使用 react 和 redux(在您的问题中标记)
const { Provider, useDispatch, useSelector } = ReactRedux;
const { createStore, applyMiddleware, compose } = Redux;
const initialState = {
items: [
{
id: 1,
children: [
{
id: 2,
children: [{ id: 3, children: [] }],
},
{ id: 4, children: [] },
],
},
],
};
//action types
const ADD = 'ADD';
const REMOVE = 'REMOVE';
//action creators
const add = (item) => ({
type: ADD,
payload: item,
});
const remove = (item) => ({
type: REMOVE,
payload: item,
});
const getId = ((id) => () => id++)(5);
const recursiveAdd = (path, items) => {
const recur = (path) => (item) => {
if (item.id === path[0] && path.length === 1) {
return {
...item,
children: item.children.concat({
id: getId(),
children: [],
}),
};
}
if (item.id !== path[0]) {
return item;
}
return {
...item,
children: item.children.map(recur(path.slice(1))),
};
};
return items.map(recur(path));
};
const recursiveRemove = (path, items) => {
const ID = {};
const recur = (path) => (item) => {
if (item.id === path[0] && path.length === 2) {
return {
...item,
children: item.children.filter(
({ id }) => id !== path[1]
),
};
}
if (item.id !== path[0]) {
return item;
}
return {
...item,
children: item.children.map(recur(path.slice(1))),
};
};
return recur([ID].concat(path))({
id: ID,
children: items,
}).children;
};
const reducer = (state, { type, payload }) => {
if (type === ADD) {
return {
...state,
items: recursiveAdd(payload, state.items),
};
}
if (type === REMOVE) {
return {
...state,
items: recursiveRemove(payload, state.items),
};
}
return state;
};
//selectors
const selectItems = (state) => state.items;
//creating store with redux dev tools
const composeEnhancers =
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
reducer,
initialState,
composeEnhancers(
applyMiddleware(() => (next) => (action) =>
next(action)
)
)
);
const Item = React.memo(function ItemComponent({
item,
add,
remove,
path,
}) {
const currentPath = path.concat(item.id);
return (
<li>
{item.id}
<button onClick={() => add(currentPath)}>Add</button>
<button onClick={() => remove(currentPath)}>
Remove
</button>
{item.children && Boolean(item.children.length) && (
<ul>
{item.children.map((child) => (
<Item
key={child.id}
item={child}
add={add}
remove={remove}
path={currentPath}
/>
))}
</ul>
)}
</li>
);
});
const ROOT = [];
const App = () => {
const items = useSelector(selectItems);
const dispatch = useDispatch();
const addItem = React.useCallback(
(item) => dispatch(add(item)),
[dispatch]
);
const removeItem = React.useCallback(
(item) => dispatch(remove(item)),
[dispatch]
);
return (
<ul>
{items.map((item) => (
<Item
key={item.id}
item={item}
add={addItem}
remove={removeItem}
path={ROOT}
/>
))}
</ul>
);
};
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/redux/4.0.5/redux.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-redux/7.2.0/react-redux.min.js"></script>
<div id="root"></div>
推荐阅读
- canvas - 在 webgl 中,透视相机被添加到画布或 3D 模型本身?
- google-cloud-platform - 为 GCP Bucket 中所有未来上传的对象设置默认元数据
- android - 无法同步 Gradle 项目并显示消息“读取超时”
- rxjs - 无法将 Observable 转换为 ConnectableObservable
- php - wp_query wordpress
- java - 我想创建一个包含我所有函数的 .class 文件。我无法编译它。我应该进口什么?
- c# - 我正在处理仅包含 3 个字段的新用户注册表单,用户名、密码和确认密码
- sql - 使用 ADO.net 将 100000 条记录从数据库绑定到 asp.netmvc 中的数据表时出现问题
- c# - 如何返回对结构列表中特定结构的引用?
- c# - 多个 webapi 的 IIS 重定向问题