微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我不知道为什么我变得未定义我怎样才能做到这一点?

如何解决我不知道为什么我变得未定义我怎样才能做到这一点?

我正在搜索用户,当我找到它时,我想将其设置为配置状态。现在,当我在子数组中搜索时,我收到一个类型错误提示“无法读取未定义的属性 'children'”。为什么会这样?我该如何解决? 如果没有用户名,我可以设置配置状态。此外,如果我放入 console.log 或更改某些内容并保存,我会注意到页面会重新加载并且我搜索的对象已设置,即使之前有人说无法读取未定义的属性“孩子”。
这里是代码

  const [config,setConfig] = useState({});



 const makeTree = (users) => {
    let tree = {children:[]};
    for (const person of users) {
      if (!person.report) {
        tree = { ...person,...tree };
      } else {
        if (tree.name === person.report) {
          tree.children.push(person);
        } else {
          tree.children?.forEach(child => {
            if (child.name === person.report) {
              child.children = [];
              child.children.push(person)
            }
          })
        }
      }
    }

    return tree;
  };

  const searchInChildren = (children,name) => {
    for (let i = 0; i<children.length; i++) {
      
      if (children[i]?.name === name) {
        setConfig(getConfig(children[i]));
      }
       else if (children[i] && children[i].children && children[i].children.length > 0) {
        searchInChildren(children[i].children,name)
      } else {
        console.log("not found!")
      }
    }
  };

  useEffect(() => {
    fetch("http://localhost:4000/schema")
      .then((response) => response.json())
      .then((data) => {
        if (username) {
          const treeObj = {...makeTree(data)};
          console.log("tree",treeObj);
          const regex = new RegExp(username,"gi");
          for (let i = 0; i < data.length; i++) {
            if (regex.test(data[i].name)) {
              if (treeObj.name === data[i].name) {
                setConfig(getConfig(treeObj))
              } else {
                console.log("treeObj.children",treeObj.children,data[i] );
                searchInChildren(treeObj.children,data[i].name)
              }

            }
          }
        } else {
          setConfig(getConfig(makeTree(data)));
        }
        if(deleteSearch){
            console.log("hi",deleteSearch);
            setConfig(getConfig(makeTree(data)));
        }
      });
  },[username,deleteSearch])

;

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。