首页 > 解决方案 > 为什么 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>&nbsp;&nbsp;
          {/* 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在前端删除了带有索引的组件

标签: javascriptreactjsfrontendstate

解决方案


推荐阅读