Skip to content

修复聊天记录多时markdown渲染卡顿问题 #119

@CassiopeiaCode

Description

@CassiopeiaCode

问题

聊天记录多了以后,markdown渲染会很卡,用户体验不太好。

现状

  • 每次都重新渲染markdown,没有缓存
  • 消息多的时候页面会卡住
  • 代码里有些优化被注释掉了

解决思路

项目要需要编译成不同版本,所以推荐两种解决方法:

1. 开启被注释的React缓存

把注释掉的RenderMarkdown组件恢复,加上缓存:

function IRenderMarkdown(props) {
  const renderedContent = React.useMemo(() => {
    return render(props.children);
  }, [props.children]);

  return (
    <div
      className="markdown-body text-sm lg:text-base"
      dangerouslySetInnerHTML={{ __html: renderedContent }}
    />
  );
}
export const RenderMarkdown = React.memo(IRenderMarkdown);

2. 简单的缓存机制

用Map缓存渲染结果:

const markdownCache = new Map();

const renderWithCache = (content) => {
  if (markdownCache.has(content)) {
    return markdownCache.get(content);
  }
  
  const rendered = render(content);
  
  // 缓存太多了就清理一下
  if (markdownCache.size > 500) {
    markdownCache.clear();
  }
  
  markdownCache.set(content, rendered);
  return rendered;
};

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions