Ant design's Tree tree control useMemo first gets the initial data and then executes return

According to the content of the document:
before 3.4.0: there can be many tree nodes, but when setting checkable, it will take more calculation time, so we cache some calculation results (this.treeNodesStates) to reuse to avoid multiple Repeat calculations to improve performance. But this also brings some limitations, when you load tree nodes asynchronously, you need to render the tree like this:

{
    
    
  this.state.treeData.length ? (
    <Tree>
      {
    
    this.state.treeData.map((data) => (
        <TreeNode />
      ))}
    </Tree>
  ) : (
    'loading tree'
  );
}

Solution:

  const treeData = useMemo(() => {
    
    
  //新增一个defaultData函数会一直循环,所以就defaultData.length
  }, [defaultData.length, searchValue]);
     {
    
    
            treeData?.length ? (
              <Tree
                onExpand={
    
    onExpand}
                expandedKeys={
    
    expandedKeys}
                autoExpandParent={
    
    autoExpandParent}
                treeData={
    
    treeData}
                defaultExpandAll={
    
    true}
              />
            ) : (
              'loading tree'
            )
          }

The following is the stupid operation that I did not read the bottom of the document, and I have been tossing for a few days:
first, I deleted the function of generateData(z) to initialize the data, and then replaced const defaultData: DataNode[] = [];it const [defaultData, setDefaultData] = useState<DataNode[]>([])with a new const isflag = React.useRef(0);identifier. The purpose is to wait Execute the useMemo function again

  const treeData = useMemo(() => {
    
    
    getorganizationsRelations().then((res) => {
    
    
      //在接口里获取到想要的数据
      setDefaultData(data)
    })
    
 if (defaultData?.length !== 0 && defaultData?.length !== undefined) {
    
    
  	  // 执行generateList函数返回loop()函数
 	  generateList(defaultData)
      return loop(defaultData);
    } else {
    
    
      //一开始defaultData是[],所以先执行这一步,让 isflag.current 的值发生变化,然后再次执行useMemo函数,此时defaultData就会有值走上面
      isflag.current = 1
    }
  }, [isflag.current, searchValue]);

Guess you like

Origin blog.csdn.net/qq_41160739/article/details/128454741