负载两次从脚本中使用的效果效果渲染表?
我在下一个网站中使用hubspot表单 - 我想在代码中看到的页面加载上的表单。
不期望的效果是表格呈现两次,我想在系统中构建,因此仅在页面加载上呈现,这就是这样。我该如何实现?
我试图遵循它来解决它,但不起作用 https://www.youtube.com/观看?v = kzh6yxw0zw4 。
下面的代码
useEffect(() => {
let isCancelled = false;
const script = document.createElement('script');
script.src = "//js-eu1.hsforms.net/forms/v2.js";
document.body.appendChild(script)
if (!isCancelled) {
script.addEventListener('load', () => {
if (window.hbspt){
hubspotForm();
}
})
}
return () => {
isCancelled = true
};
}, [])
I am using a hubspot form in my next.js site - I want to render the form on page load as you can see in the code.
The undesired effect is that the form renders twice, I want to build in a system so it only renders on page load and thats it. How do I achieve this?
I tried to follow this to solve it but did not work https://www.youtube.com/watch?v=KzH6YxW0zW4.
Code below
useEffect(() => {
let isCancelled = false;
const script = document.createElement('script');
script.src = "//js-eu1.hsforms.net/forms/v2.js";
document.body.appendChild(script)
if (!isCancelled) {
script.addEventListener('load', () => {
if (window.hbspt){
hubspotForm();
}
})
}
return () => {
isCancelled = true
};
}, [])
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
删除严格模式是您不喜欢的。我相信,如果您这样做:
它应该很好。我准备了有关该主题的详细说明(为什么使用效果是两次运行以及如何处理。 >在这里如果您可能想看看。删除严格模式是一种简单的方式,但您不应该选择它。
Removing strict mode is something that you should not prefer. I believe if you do this:
it should work fine. I prepared a detailed explanation of the topic (why useEffect is running twice and how to handle it.) here if you might want to have a look. Removing Strict mode is an easy out way but you should not choose it.
从您的索引中删除严格的模式,这应该可以解决问题。
Remove strict mode from your index.js, that should do the trick.
检查
React
和React-dom
的版本如果您使用的是React V18的最后版本。由于具有严格的模式和同时渲染功能,因此执行
usefeft()
挂钩即使设置一个空的依赖项数组,也可以运行两倍。您可以从
next.config.js
文件禁用React strictmode,这应该有助于解决您的问题
check the version of
react
andreact-dom
in thepackage.json
fileif you're using the lastest version of react v18. Because of the react strict mode and concurrrent rendering feature it executes the
useEffect()
hook to run twice even the if you set an empty dependency array.you can disable react strictmode from
next.config.js
fileit should help to fix your problem
您可以做类似的事情:
另外,检查您是否不重新安装组件,两次触发脚本的事实表明,在组件外部的某个地方重新安装了负载,这可能会导致性能问题。
You can do something like this:
Also, check that you're not re-mounting your component, the fact that your script is triggered twice suggests that somewhere outside your component is re-mounted on load, which might cause performance issues.