【问题标题】:React freezes when trying to add million elements尝试添加数百万个元素时 React 冻结
【发布时间】:2019-07-17 05:20:04
【问题描述】:

我正在制作一个带有树的应用程序,其中每个项目都有 10^depth 子元素(最大深度为 5)。一切正常,但我打开树枝越深,渲染它所需的时间就越多。在第 5 级它甚至可以冻结。

这是我的代码:

      class TreeNode extends React.Component {

      constructor(props) {
          super(props)
          this.state = {
              expanded: false,
              depth: this.props.parentDepth + 1
          }
          this.treeExpand = this.treeExpand.bind(this);
      }

      treeExpand() {
          if (this.state.depth <= 5) {
              this.setState({
                  expanded: !this.state.expanded
              });
          }
      }

      prepareNodes(){
        if (this.state.expanded) {
            var tree = [];
            for (var i = 1; i < Math.pow(10, this.props.parentDepth + 1) + 1; i++) {
                tree.push(<TreeNode parentDepth={this.state.depth} selfNum={i} parentStack={this.props.parentStack+' > '+this.props.selfNum} />);
            }
            return <ul>{tree}</ul>;
        }else{
            return null;
        }
      }


      render() {
          return (
              <li key={this.props.parentStack+'-'+this.props.selfNum}>
                <span onClick={this.treeExpand}>
                   {(this.state.expanded ? '[-]' : '[+]')}
                   {this.props.selfNum}
                   ({this.props.parentStack})
                 </span>
                   {this.prepareNodes()}
                 </li>
          );
      }
  }

  class TreeSection extends React.Component {

      constructor(props) {
          super(props)
      }


      render() {
          var tree = [];
          for (var i = 1; i < 11; i++) {
              tree.push(<TreeNode parentDepth={1} selfNum={i} parentStack={'root'}/>);
          }
          return (
              <ul>
                {tree}
              </ul>
          );
      }
  }


  ReactDOM.render(
      <TreeSection />,
      document.getElementById('root')
  );

Image: expanded tree view

我认为这可能是由于 prepareNodes() 函数返回的数组太大造成的。如何修复?我是 React 新手。

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    在不知道更多细节的情况下,我可以说有这么多节点,对象肯定应该被分解成逻辑段。如果数据是一个大集合,则需要由您的服务器对其进行分页 - 您的浏览器(和机器)只能处理这么多。根据提供的信息,我认为这不是前端问题,而是您的数据如何提供给您的前端。

    【讨论】:

    • 数据在客户端生成。浏览器本身也可以很好地呈现 1000000 个元素,问题一定是内存溢出。
    猜你喜欢
    • 2022-08-19
    • 2015-02-16
    • 1970-01-01
    • 2012-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多