reactjs 如何访问TypeScript中节点的“邻居”属性

sczxawaw  于 2023-04-29  发布在  React
关注(0)|答案(1)|浏览(103)

我正在用react-force-graph-2d构建一个图,并从一个示例中获得以下片段:

const data2 = useMemo(() => {
        const gData = genRandomTree(80);

        // cross-link node objects
        gData.links.forEach((link) => {
          const a = gData.nodes[link.source];
          const b = gData.nodes[link.target];
          !a.neighbors && (a.neighbors = []);
          !b.neighbors && (b.neighbors = []);
          a.neighbors.push(b);
          b.neighbors.push(a);

          !a.links && (a.links = []);
          !b.links && (b.links = []);
          a.links.push(link);
          b.links.push(link);
        });

        return gData;
      }, []);

所有对neighborslinks的引用都显示错误,并显示消息“*Property 'neighbors' does not exist on type '{ id:any;}“. ”和“ 属性“links”在类型“{ id:“**”分别。
我已经尝试用上述属性定义类型,但这并没有改变任何东西:

type gDataNodeType = {
id: any;
neighbors: any[];
links: any[];
}

然后将const ab改为:

const a:gDataNodeType = gData.nodes[link.source];
const b:gDataNodeType = gData.nodes[link.target];

但是我得到了错误:
类型“{ id:any;}”缺少类型“gDataNodeType”中的以下属性:邻居,链接
我做错了什么?

编辑

下面是GetRandomTree的函数:

export function genRandomTree(N = 300, reverse = false) {
  return {
    nodes: [...Array(N).keys()].map(i => ({ id: i })),
      links: [...Array(N).keys()]
    .filter(id => id)
    .map(id => ({
      [reverse ? 'target' : 'source']: id,
      [reverse ? 'source' : 'target']: Math.round(Math.random() * (id-1))
    }))
  };
}
cidc1ykv

cidc1ykv1#

linksneighbors属性未声明。你可以在genRadomTree函数中声明和初始化它们:

export function genRandomTree(N = 300, reverse = false) {
  return {
    nodes: [...Array(N).keys()].map(i => (
         {id: i, neighbors: [] as number[], links: [] as number[]})),
    links: [...Array(N).keys()]
    .filter(id => id)
    .map(id => ({
      [reverse ? 'target' : 'source']: id,
      [reverse ? 'source' : 'target']: Math.round(Math.random() * (id-1))
    }))
  };
}

然后就可以删除那两行了,因为那些属性已经初始化了

!a.neighbors && (a.neighbors = []);
!b.neighbors && (b.neighbors = []);

相关问题