javascript - 为什么 React 不删除所需的组件而是删除最后一个兄弟?
问题描述
import * as React from "react";
const Node = ({ setSelfStateOnParent, removeSelfFromParent, id }) => {
const [state, setState] = React.useState({
name: "", // Stores name of node
children: [], // Stores the children of this node (sub-nodes)
});
function updateName(updatedName) {
setState({ ...state, name: updatedName });
}
function updateChildren(updatedChildren) {
setState({ ...state, children: updatedChildren });
}
function addChild() {
updateChildren([...state.children, { name: "", children: [] }]);
}
React.useEffect(() => {
/* If this is a sub-node, update element in parent's
* state.children array containing info about this sub-node
*/
if (setSelfStateOnParent) {
setSelfStateOnParent(state);
}
}, [state]);
return (
<div className="Node">
<header>
<div className="name">
<span>{id}</span>
{/* Text field to update state.name */}
<input
type="text"
value={state.name}
onChange={(e) => updateName(e.target.value)}
/>
</div>
<div className="btn_group">
<button
onClick={() => {
addChild();
}}
>
add child
</button>
{removeSelfFromParent && (
<button
onClick={() => {
if (removeSelfFromParent) removeSelfFromParent();
}}
>
delete
</button>
)}
</div>
</header>
{state.children && (
<ul className="children">
{state.children.map((child, childIndex) => (
<li className="child_node" key={childIndex}>
<Node
id={childIndex}
setSelfStateOnParent={(childState) => {
// Copy parent's children array to edit and update
const updatedChildren = [...state.children];
/*
* Updates the array with sub-nodes own state
*/
updatedChildren[childIndex] = { ...childState };
updateChildren(updatedChildren);
}}
removeSelfFromParent={() => {
const updatedChildren = [...state.children];
/* Removes this sub-node's info from
* parent's state.children
*/
const removedChild = updatedChildren.splice(childIndex, 1);
updateChildren(updatedChildren);
}}
/>
</li>
))}
</ul>
)}
</div>
);
};
export default Node;
当我尝试在 React DevTools 中调试时state.children
,我想删除的元素被删除了,但它仍然显示在前端。例如,当有索引为 0..4 的子节点时,我在索引为的组件上按删除2
;在 React DevTools 中,带有索引的组件2
被删除,但它4
在前端删除了带有索引的组件
解决方案
推荐阅读
- liferay-7 - 会话到期时 Liferay 服务器未重定向到默认页面
- node.js - 如何修复:猫鼬在使用相同文档的备用 doc.save() 执行时给出验证错误
- android - Android ConstraintLayout Barrier 以编程方式不起作用
- javascript - react-native 应用程序卡在启动画面上
- java - JDBC 连接意外关闭
- javascript - 如何从 OSM 中删除标记
- shellexecute - AppLocker 阻止 ShellExecute 而不给出错误消息
- reactjs - 在 2 个值之间过滤状态并重新渲染它
- reactjs - Next-Redux-Wrapper 不更新 SSR 存储
- dependency-injection - Flutter:(如何)我可以拥有每个依赖于 Provider 的小部件的 PageView 吗?