javascript 如何在 reactjs 中管理树组件中的状态

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20503559/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 18:38:13  来源:igfitidea点击:

How to manage state in a tree component in reactjs

javascripttreereactjs

提问by Jared Forsyth

I've been struggling this for a couple of days, trying to figure out the "react" way to do it.

我已经为此苦苦挣扎了几天,试图找出“反应”的方式来做到这一点。

Basically, I have a tree, a list of lists (of lists ...) that can be arbitrarily nested, and I want a component that will display this and also enable rearrangement.

基本上,我有一个树,一个可以任意嵌套的列表(列表......)列表,我想要一个可以显示它并启用重新排列的组件。

Here's my data:

这是我的数据:

var data = [{
      id: 1
    }, {
      id: 2, children: [
        {
          id: 3, children: [{id: 6}]
        }, {
          id: 4
        }, {
          id: 5
        }]
    }]

My first pass was to just have a single "tree" component that builds the nested lists of DOM elements in its render function (look at the code here). That actually worked pretty well for small numbers of elements, but I want to be able to support hundreds of elements, and there was a very high re-render cost when an element was moved within the tree (~600ms when there were a few hundred elements).

我的第一遍是只有一个“树”组件,它在其渲染函数中构建嵌套的 DOM 元素列表(查看此处的代码)。对于少量元素,这实际上效果很好,但我希望能够支持数百个元素,并且当一个元素在树内移动时,重新渲染成本非常高(大约 600 毫秒,当有几百个元素时)元素)。

So I think I'll have each "node" of the tree be it's own instance of this component. But here's my question (sorry for the long intro):

所以我想我会让树的每个“节点”成为这个组件的自己的实例。但这是我的问题(抱歉,介绍太长了):

Should each node dynamically query for the list it's children's IDs from a central "database" and store that in state? Or should the top-most node load the whole tree and pass everything down through props?

每个节点是否应该从中央“数据库”动态查询它的子节点 ID 列表并将其存储在状态中?或者最顶层的节点是否应该加载整个树并通过 props 传递所有内容?

I'm still trying to wrap my mind around how state & props should be handled & divvied up.

我仍在努力思考 state 和 props 应该如何处理和划分。

Thanks

谢谢

回答by Ross Allen

I wanted to try out the tree structure with React and came up with a simple component that hides subtrees when you click on <h5>. Everything is a TreeNode. Is this similar to what you were thinking?

我想用 React 尝试树结构,并想出了一个简单的组件,当你点击时隐藏子树<h5>。一切都是一个TreeNode. 这和你想的一样吗?

You can see it in action in this JSFiddle: http://jsfiddle.net/ssorallen/XX8mw/

你可以在这个 JSFiddle 中看到它的实际效果:http: //jsfiddle.net/ssorallen/XX8mw/

TreeNode.jsx:

树节点.jsx

var TreeNode = React.createClass({
  getInitialState: function() {
    return {
      visible: true
    };
  },
  render: function() {
    var childNodes;
    if (this.props.node.childNodes != null) {
      childNodes = this.props.node.childNodes.map(function(node, index) {
        return <li key={index}><TreeNode node={node} /></li>
      });
    }

    var style = {};
    if (!this.state.visible) {
      style.display = "none";
    }

    return (
      <div>
        <h5 onClick={this.toggle}>
          {this.props.node.title}
        </h5>
        <ul style={style}>
          {childNodes}
        </ul>
      </div>
    );
  },
  toggle: function() {
    this.setState({visible: !this.state.visible});
  }
});

bootstrap.jsx:

bootstrap.jsx

var tree = {
  title: "howdy",
  childNodes: [
    {title: "bobby"},
    {title: "suzie", childNodes: [
      {title: "puppy", childNodes: [
        {title: "dog house"}
      ]},
      {title: "cherry tree"}
    ]}
  ]
};

React.render(
  <TreeNode node={tree} />,
  document.getElementById("tree")
);

回答by chenglou

Seems like it'd be nicer to pass everything down as props, as this will prevent you from the trouble of managing individual insertion/deletion. Also, like the comments said, the keyattributes prevents a huge chunk of unnecessary re-rendering.

似乎将所有内容作为 props 传递会更好,因为这将防止您管理单个插入/删除的麻烦。此外,正如评论所说,这些key属性可以防止大量不必要的重新渲染。

You might want to check this link: http://facebook.github.io/react/blog/2013/11/05/thinking-in-react.html. It describes the kind of dilemma you're having and how to approach it.

您可能想查看此链接:http: //facebook.github.io/react/blog/2013/11/05/thinking-in-react.html。它描述了您遇到的困境以及如何解决它。

(Coincidentally, I've made a react tree view a while ago: https://github.com/chenglou/react-treeview. Take whatever you want from it!)

(巧合的是,我前段时间制作了一个 React 树视图:https: //github.com/chenglou/react-treeview。从中获取任何你想要的!)

回答by TGH

Here is a quick example of how to create a treeview using React and Flux. http://www.syntaxsuccess.com/viewarticle/5510d81be1ce52d00e93da55

这是如何使用 React 和 Flux 创建树视图的快速示例。 http://www.syntaxsuccess.com/viewarticle/5510d81be1ce52d00e93da55

The React component is recursive and state is managed using Flux.

React 组件是递归的,状态是使用 Flux 管理的。