首页 > 解决方案 > Performance benefits to dangerouslySetInnerHTML

问题描述

I have a list of items and a user that wants to search those items. When the user’s search value matches the name of an item, I want to render that item with the matching part of the item's name in bold. For example:

const items = [‘milk’, ‘whole milk’, ‘2% milk’]
const searchValue = ‘milk’;

 /* outputted HTML */

<ul>
     <li>
          <Strong>milk<Strong>
     </li>
    <li>
          whole <Strong>milk<Strong>
    </li>
    <li>
          2% <Strong>milk<Strong>
    </li>
</ul>

The application is written in React and I wrote the following:

render() {
   const { items, searchValue } = this.props;
   return (
      <ul>
         {items.map((item) => {
            const parts = item.split(new RegExp('(' + searchValue + ')'));
            if (parts.length === 1) return null;
            else return <li key={item}>{parts.filter((part) => (part === searchValue ? <strong>{part}</strong> : part))}</li>;
         })}
      </ul>
  );
}

The code above preforms poorly sometimes taking seconds to render. This is unsurprising since a simple searchValue such as "a" can result in hundreds of items being rendered. I did notice however that if I use dangerouslySetInnerHTML, these performance problems disappear:

 render() {
   const { items, searchValue } = this.props;
   return (
      <ul>
         {items.map((item) => {
              if (!item.includes(searchValue)) return null;
              const boldedItem = item.replace(new RegExp(searchValue), (match) => '<Strong>' + match + '</Strong>');
              return <li key={item} dangerouslySetInnerHTML={{ __html: boldedItem }}></li>;
         })}
      </ul>
  );
}

Does anyone know why dangerouslySetInnerHTML is preforming better here?

While I'll likely solve this problem by limiting the rendered search results (ex: https://github.com/bvaughn/react-window) instead of using dangerouslySetInnerHTML, I still want to know what is happening under the hood here.

标签: javascriptreactjs

解决方案


推荐阅读