简体   繁体   English

如何在reactjs中重新初始化外部JavaScript?

[英]How to reinitialize external javascript in reactjs?

I am dynamically adding script tag in componentDidMount() on first load. 我在第一次加载时在componentDidMount()中动态添加了脚本标签。 Next when I route to that component I just need the script to re-execute again. 接下来,当我路由到该组件时,我只需要脚本重新执行即可。 Hence I am calling window.__sharethis__.initialize(); 因此,我正在调用window.__sharethis__.initialize(); . This function gets called, but it doesn't update the count. 该函数被调用,但不会更新计数。 What function I need to call so that I can re-execute the script. 我需要调用什么函数才能重新执行脚本。

const script1 = document.getElementById("shareThisId");
            if (script1) {
                window.__sharethis__.initialize();
            } else {
                const script = document.createElement("script");

                script.src =
                    "//platform-api.sharethis.com/js/sharethis.js#property=[some-id]&product=sop?r=" +
                    Math.random();
                script.async = true;
                script.id = "shareThisId";

                document.body.appendChild(script);
            }

Note that, on browser reload, the count gets updated, but not when I route using react-router. 请注意,在浏览器重新加载时,计数会更新,但在使用react-router进行路由时不会更新。

I have also tried removing the script from DOM and adding it again in componentDidMount(). 我也尝试过从DOM中删除脚本,然后再次将其添加到componentDidMount()中。 But, removing and updating from dom, will not result in the execution of script. 但是,从dom中删除和更新不会导致脚本的执行。

Since you are using webpack, you can just import the js in the component file. 由于您使用的是webpack,因此只需将js导入组件文件中即可。 Whenever the component mounts just initiate the function. 只要安装了组件,就启动该功能。

import '../../js/example.js'

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

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