1

我正在使用反应,我想将一个组件拆分为子组件,以优化它(我正在使用 mobX 并尝试实现一些作为此处的列表示例https://mobxjs.github.io/mobx/best/react-performance。 html )

然而,这样做似乎我被迫引入额外的 dom 元素。考虑一个 NodeComponent 来渲染一棵树

const NodeComponent = ({node}) => (
  <div>
    <div that access some stuff with node properties/>
    {children.map(childNode => <NodeComponent node={childNode} />)}
  </div>
);

这是伪代码,我希望你明白。

如何将第一个内部 div 与递归渲染分开,而不在子级周围引入额外的包装 dom 元素(如下面的 div)?

const NodeComponent = ({node}) => (
  <div>
    <div that access some stuff with node properties/>
    **<useless div>**
      {children.map(childNode => <NodeComponent node={childNode} />)}
    **<useless /div>**
  </div>
);

如果我有数千个节点,这意味着有数千个额外的无用 dom 元素,而且我正在移植具有特定 dom 结构和 CSS 的现有控件,如果我想拆分它们,我必须更改它。

TL;博士; 我可以将此组件拆分为 2,以便在不需要更改 DOM 输出的情况下获得不重新渲染所有子级的 mobx 优化吗?

或者再次:为什么纯粹的优化/重构迫使我修改我的 dom 最终结果?

4

2 回答 2

1

For the time being, I will end up using something like https://github.com/mwiencek/react-packages in order to make React/JSX happy and not being obliged to change my dom structure. It's more of a hacky workaround than a proper solution, but it does fix my problem.

Hopefully when https://github.com/facebook/react/issues/2127 gets fixed I won't need it anymore.

Thanks everybody for the help anyway, I really appreciate it (and thanks once more to @mweststrate for MobX in general :) )

于 2016-08-19T09:45:00.473 回答
0

这似乎是一个递归数据结构。我认为您可以很好地将其拆分为多个组件,而无需使用不必要的节点:

Node = observer({ node } => (
  <div>
    {node.title}
    <Children={node.children} />
  </div>
))

Children = observer({ children } => (
  !children ? null :
  <ul>
    {children.map(child => <Node node={child} />
  </ul>
))

我认为这是您可以获得的最小树,并且 mobx 可以很好地优化它,因为子集合被呈现为单独的组件。您可能认为ul不需要 ,但我认为出于所有实际样式的原因,您可能需要这个 dom 节点,否则很难在不定位父母的情况下定位后代。

Besides that, I wouldn't care too much about additional nodes in your DOM without some emperical proof for it being a bottleneck. It might be very well that it doesn't matter at all, or that for example your CSS selectors are a lot faster with the ul then without the ul

于 2016-08-18T19:29:54.297 回答