简体   繁体   English

防止React危险地调用SetInnerHTML客户端

[英]Prevent React from calling dangerouslySetInnerHTML client side

I use dangerouslySetInnerHTML for rendering a JS script tag in one of my components for loading DFP ad units. 我使用dangerouslySetInnerHTML使用SetInnerHTML在我的一个组件中呈现JS脚本代码,以加载DFP广告单元。 My page is first rendered on the server then the same code loads also on the client. 我的页面首先在服务器上呈现,然后相同的代码也在客户端上加载。

The problem is that the DFP code uses document.write to inject a script and as soon as my client side code loads it cancels this because most probably dangerouslySetInnerHTML gets re-called and replaces the script first rendered on the server. 问题是DFP代码使用document.write来注入脚本,并且一旦我的客户端代码加载它便取消了此操作,因为很有可能dangerouslySetInnerHTML调用了SetInnerHTML并替换了首先在服务器上呈现的脚本。

Any idea of how to go around this? 关于如何解决这个问题的任何想法?

If you don't want the contents of the component being changed after the initial render, define shouldComponentUpdate in your component and set it to always return false . 如果您不希望在初始渲染后更改组件的内容,请在组件中定义shouldComponentUpdate并将其设置为始终返回false That way you can prevent the component from ever updating beyond the initial render. 这样,您可以防止组件在初始渲染后进行更新。

The problem was that there were some rendering differences between server and client so React was patching parts of the DOM (or maybe all of it) thus breaking the ad's iframe. 问题在于服务器和客户端之间存在一些渲染差异,因此React正在修补DOM的部分(或全部),从而破坏了广告的iframe。

This was happing only in production so the warnings were not showing up. 这仅在生产中出现,因此警告没有出现。

More precisely the difference was caused by moment js rendering some dates relative to the machine's time zone which was different from server to client. 更确切地说,差异是由于js渲染相对于机器时区的某些日期而导致的,这在服务器与客户端之间是不同的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM