简体   繁体   English

在将js脚本添加到html后的react.js App中,它不起作用

[英]In react.js App after adding js script to html it doesn't work

In my react app I have a code like this 在我的反应应用程序中,我有一个这样的代码

<div>{someVariable}</div>
const someVariabe = "<p id="test">Test</p>
<script>setInterval(() => alert('!!!'), 5000)</script>"

after rendering my HTML looks like 渲染我的HTML后看起来像

<div>
   <p id="test">Test</p>
   <script>setInterval(() => alert('!!!'), 5000)</script>
</div>

But the script doesn't work, why? 但脚本不起作用,为什么? It doesn't need DOM, I tried to reload the page after adding the script but nothing happens. 它不需要DOM,我尝试在添加脚本后重新加载页面但没有任何反应。

  1. Maybe the system doesn't understand that it is script and there is another way to add it? 也许系统不理解它是脚本,还有另一种方法来添加它?
  2. Maybe the script will be running just in head or body directly? 也许剧本会直接在头部或身体中运行?

You should place your setInterval either in a lifecycle method, in case you use classes, or in an effect hook if you're using hooks: 您应该将setInterval放在生命周期方法中,以防您使用类,或者在您使用挂钩时放在效果挂钩中:

Classes: 类别:

componentDidMount () {
  setInterval(() => alert('!!!'), 5000)
}

Hooks: 钩:

useEffect(() => {
  setInterval(() => alert('!!!'), 5000)
}, []) // [] to mimic didMount

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

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