javascript - 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.
解决方案
推荐阅读
- unity3d - 如何用 ArCore 固定室内环境中的物体?
- python - 如果文件为空则中断程序
- javascript - 如何在 Jquery 模板中分配局部变量
- jquery - 如何避免在jquery中多次触发ajax回调?
- c# - 使用 LINQ 合并多个 PDF
- excel - 根据条件删除列中的重复项
- perl - Log::Log4Perl 不同的日志记录目的地取决于 LogLevel
- hyperledger - 安装超级账本作曲家时出错,出现构建错误
- r - 将 ... 中的参数映射到 summarise(.funs = funs(f1, f2), ...) 中的每个函数
- r - 当我在预测函数中使用反应对象时,R闪亮显示错误