【问题标题】:Fastest way to display data with ReactJS使用 ReactJS 显示数据的最快方法
【发布时间】:2018-08-12 11:04:33
【问题描述】:

我正在尝试使用 Electron 和 ReactJS 为自己创建一个泥(多用户地牢)客户端,用于学习和挑战自己。但似乎我在这次挑战中失败了。

我正在使用 telnet-stream 从服务器获取数据。

来自服务器的数据具有 ansi 代码,因为它是基于 telnet 的通信。

问题在于速度。我不确定我是否做得对,但这里是负责显示数据的组件:

import React, { Component } from 'react';
import styles from './style.css';

type Props = {
  output: Array<any>
};

export default class ActionWindow extends Component<Props> {
  props: Props;

  componentDidMount() {
    this.scrollToBottom();
  }

  componentDidUpdate() {
    this.scrollToBottom();
  }

  scrollToBottom() {
    this.el.scrollIntoView({ behavior: 'smooth' });
  }

  render() {
    const output = this.props.output.map(chunk => chunk
        .replace('&', '&amp;')
        .replace('<', '&lt;')
        .replace('>', '&gt')
        .replace(/\x1b\[(\d+);(\d+);?(\d+)?m/g, '</span><span class="c-$1 c-$2 x-$3">')
    );
    return (
      <div className={styles.actionWindowWrapper}>
        <span dangerouslySetInnerHTML={{ __html: output }} />
        <div ref={el => { this.el = el; }} />
      </div>
    );
  }
}

这是正确的方法,还是有更快的方法?数据通过 props 来自主 App 组件。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    为什么要使用“dangerouslySetInnerHTML”?因为您将输出映射到 html 元素,所以您可以编写:

    render() {
    
    return (
      <div className={styles.actionWindowWrapper}>
        this.props.output.map(chunk => chunk
        .replace('&', '&amp;')
        .replace('<', '&lt;')
        .replace('>', '&gt')
        .replace(/\x1b\[(\d+);(\d+);?(\d+)?m/g, '<span></span class="c-$1 c-$2 x-$3">')
        <div ref={el => { this.el = el; }} />
      </div>
    );
    

    }

    我不完全理解你的正则表达式 '.replace(/\x1b[(\d+);(\d+);?(\d+)?m/g, '')' 我不认为由于结束标记而输出正确的 html

    【讨论】:

    • 因为 ansi 颜色代码替换是这样的,并且出于速度目的,我将输出发布在 标签之间。并且没有危险的SetInnerHTML,它不会处理跨度标签并将转义标签。
    • 好的,这篇文章中的评论说使用 domElement。 innerHTML 比 dangerouslySetInnerHTML 更快。 stackoverflow.com/questions/37337289/… 当不使用 map 迭代每个块时,也许你也赢得了一些性能,而是首先对输出数组进行字符串化?通过这种方式,您的替换调用次数要少得多
    猜你喜欢
    • 1970-01-01
    • 2014-06-15
    • 2015-08-23
    • 1970-01-01
    • 1970-01-01
    • 2016-08-03
    • 1970-01-01
    • 1970-01-01
    • 2014-08-31
    相关资源
    最近更新 更多