简体   繁体   English

外部js仅在刷新后加载到反应组件中

[英]External js is loading in react component only after refresh

My Component.我的组件。

import useScript from "./useScript";
function MyComponent(): JSX.Element {
useScript("https://dev-kpaymentgateway.kasikornbank.com/ui/v2/kinlinepayment.min.js", "pkey_test_20184OBD88Yvl6uplpR0kY0ZTpVz46h1Tdqyj");
return (
    <div className={greyContainer}>
        <div className={gridContainer}>

            <p id="error-summary">
                Oops something went wrong, please try again.
            </p>

            <div className="flied">
                <label className="label"> name</label>

                <div id="name"></div>
                <label> Name is invalid.</label>
            </div>

            <div className="flied">
                <label className=" label">Number</label>

                <div id="number"></div>
                <label>Number is invalid.</label>
            </div>

        </div>
        <div style={{textAlign: "right", marginBottom: 10, marginTop: 30}}>
            <form method="POST" action="https://httpbin.org/post">
                <button type="submit" className="pay-button">Pay now</button>
            </form>
        </div>

    </div>
);
}

I load script using react hook .我使用react hook加载脚本。 This script is supposed to add some field in component above.该脚本应该在上面的组件中添加一些字段。

import { useEffect } from "react";

const useScript = (url, dataKey) => {
useEffect(() => {
    const script = document.createElement("script");

    script.src = url;
    script["data-key"] = dataKey;
    script["data-lang"] = "en";
    script["data-write-log"] = true;
    script.async = true;

    document.body.appendChild(script);

    return () => { document.body.removeChild(script);};
    }, [url]);
  };

  export default useScript;

My script is loading but only after refresh the page where I have used the component MyComponent .我的脚本正在加载,但只有在刷新我使用了组件MyComponent的页面之后。 I am using react-router5 for navigation.我正在使用react-router5进行导航。

Can anybody explain why it is happening and how to overcome it.任何人都可以解释它为什么会发生以及如何克服它。

My best guess is that the kinlinepayment.min.js script was executed just fine.我最好的猜测是kinlinepayment.min.js脚本执行得很好。 But it registers an event listener for an event that already happened and will not happen again:但它为已经发生且不会再次发生的事件注册一个事件侦听器:

document.addEventListener("DOMContentLoaded",e())

You could try to dispatch that event (and all backup events if you need to support old browsers) in your useEffect:您可以尝试在您的 useEffect 中调度该事件(以及所有备份事件,如果您需要支持旧浏览器):

...
document.body.appendChild(script);

document.dispatchEvent(new Event('DOMContentLoaded')))

return ...

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

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