简体   繁体   English

重新运行一个HTML <script> in React

[英]Re-run an html <script> in React

I'm making a component in React that has Pinterest Pins pulled from an API call. 我正在React中制作一个组件,该组件具有从API调用中提取的Pinterest引脚。 The API call returns and updates a list, which render() will then populate with tags that are supposed to be converted to actual images by a script from Pinterest's website. API调用返回并更新一个列表,然后render()将使用应该由Pinterest网站上的脚本转换为实际图像的标签填充。 Something like this: 像这样:

<a data-pin-do={'embedPin'} href={'https://www.pinterest.com/pin/12345'} />

My html file includes this script, which I assume runs through the HTML code and converts the tags to something viewable. 我的html文件包含此脚本,我认为该脚本贯穿HTML代码,并将标记转换为可见的脚本。

<script async defer src="//assets.pinterest.com/js/pinit.js"></script>

However, the problem I'm running into is that the script only runs when the webpage initially loads, and then never again. 但是,我遇到的问题是,脚本仅在最初加载网页时运行,然后再也不会加载。 Since I'm adding more tags in an API call and then updating the list via the props, it means I'm left with a bunch of tags that don't get converted when the call returns. 因为我要在API调用中添加更多标签,然后通过props更新列表,所以这意味着我剩下一堆标签,这些标签在调用返回时不会转换。

I've inspected the React console & html and can confirm the tags are there, it's just that the dynamically converted tags don't show up as pins. 我已经检查了React控制台和html并可以确认标签在那里,只是动态转换后的标签没有显示为图钉。

I've already tried using jquery and document.appendChild() to add/get the script in componentDidUpdate(), but it doesn't seem to be working. 我已经尝试过使用jquery和document.appendChild()在componentDidUpdate()中添加/获取脚本,但是它似乎不起作用。 Anybody have any clue how I can get around this? 有人知道我该如何解决吗?

If you look in your devtools you should see that when the html page loads this script it is just making a GET request to the script src ( http://assets.pinterest.com/js/pinit.js ). 如果您查看自己的devtools,您应该看到html页面加载此脚本时,它只是向脚本src( http://assets.pinterest.com/js/pinit.js )发出GET请求。 So, you should be able to recreate that behavior by making a simple http GET request to that url each time you need to rerun the script. 因此,您应该能够通过在每次需要重新运行脚本时向该URL发出一个简单的http GET请求来重新创建该行为。

Try using:a do-while in your script: 尝试使用:在脚本中执行以下操作:

var repeat = 0
Do { 
// Your code goes here
repeat = repeat + 1
} while(repeat <= 10)

Note: replace 10 with times you want the script to repeat 注意:将10替换为您希望脚本重复的次数

If you wan't to add a rule to this (so it only runs when...) do: 如果您不想为此添加规则(因此它仅在...时运行),请执行以下操作:

var repeat = 'yes'
Do { 
// Your code goes here
} while(repeat == 'yes')

Now your code will only run when repeat is equal to yes 现在,您的代码仅在重复等于yes时运行

In action 在行动

<a href="javascript:repeat = 'no'">Stop repeating</a>
<a href="javascript:repeat = 'yes'">Start repeating</a>
<script>
var repeat = 'yes'
Do { 
// Your code goes here
If(var1 == var2) { repeat = 'no' }
} while(repeat == 'yes')
</script>

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

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