
本文介绍在 React 中安全、准确地渲染含 Unicode 转义序列(如 \u00e2\u0080\u0099)的 HTML 字符串,解决因编码错乱导致的乱码问题,重点提供基于 TextDecoder 的解码方案及使用注意事项。
本文介绍在 react 中安全、准确地渲染含 unicode 转义序列(如 `\u00e2\u0080\u0099`)的 html 字符串,解决因编码错乱导致的乱码问题,重点提供基于 `textdecoder` 的解码方案及使用注意事项。
在实际开发中,后端 API 有时会返回包含 Unicode 转义序列(如 \u00e2\u0080\u0099 表示右单引号 ’)的 HTML 字符串,但这些字符串若未经正确解码就直接通过 dangerouslySetInnerHTML 渲染,会导致显示为乱码(例如 We’re 而非 We’re)。这通常源于字符串被双重编码(UTF-8 字节被误作 Latin-1 解析),而非简单的 JS Unicode 转义问题。
正确的处理方式是将错误编码的字符串按原始字节重新解释为 UTF-8。以下是一个健壮的解码函数:
const decodeUnicodeBytes = (str: string): string => {
try {
// 将字符串每个字符转为其 UTF-16 码点 → 实际对应错误编码下的字节值
const bytes = new Uint8Array(
str.split('').map(char => char.charCodeAt(0))
);
return new TextDecoder('utf-8').decode(bytes);
} catch (e) {
console.warn('Failed to decode Unicode bytes:', e);
return str; // 降级:返回原始字符串,避免渲染中断
}
};
使用示例:
const apiResponse = '\n<p>We\u00e2\u0080\u0099re looking for a Customer Success Manager, Scale to join our team of five \u00e2\u0080\u009cmisfits that fit\u00e2\u0080\u009d. </p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill11824" title="shopify-app-react-router"><img
src="https://img.php.cn/upload/skill/001/246/273/6adaf20dee630206.jpg" alt="shopify-app-react-router" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill11824" title="shopify-app-react-router" class="overflowclass">shopify-app-react-router</a>
<p class="overflowclass">构建 Shopify 嵌入式应用(Embedded App)的开发技能:基于 @shopify/shopify-app-react-router + React Router v7 + Admin API 2026-04。覆盖 shopifyApp 配置、authenticate.admin 的 GraphQL/REST 调用、Webhook 校验、Session 存储、订阅计费、App Bridge 导航、部署,并新增:适用场景判断、安全最佳实践、错误处理与容错、最佳实践、常见问题 FAQ、高级场景。G</p>
</div>
<a rel="nofollow" href="/xiazai/skill11824" title="shopify-app-react-router" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>';
function MyComponent() {
const decodedHtml = decodeUnicodeBytes(apiResponse);
return (
<div dangerouslysetinnerhtml="{{" __html: decodedhtml></div>
);
}
⚠️ 重要注意事项:
-
dangerouslySetInnerHTML本身存在 XSS 风险,请确保 HTML 内容来源可信;如需渲染用户输入内容,务必先进行 HTML 消毒(例如使用DOMPurify.sanitize()); - 该解码函数适用于「UTF-8 字节被错误解析为 Latin-1 后再转义为
\uXXXX」的典型场景(常见于老旧服务端栈); - 若原始数据已是标准 JS Unicode 转义(如
\u2019),则无需此解码——React 会自动渲染为对应字符; - 建议优先推动后端修复编码问题(统一返回合法 UTF-8 字符串 + 正确
Content-Type: application/json; charset=utf-8),前端解码仅作为临时兼容方案。
通过上述方法,可精准还原智能引号(“”)、弯撇号(’)、不间断空格( )等排版友好的 Unicode 字符,提升内容专业性与可读性。










