I want to load the script from a CDN and then execute a function exposed by that script in React:
componentWillMount() {
console.log('componentWillMount is called');
const script = document.createElement('script');
script.src = 'https://foo.azurewebsites.net/foo.js';
document.body.appendChild(script);
}
componentDidMount() {
console.log('componentDidMount is called');
window.foo.render({
formId: '77fd8848-791a-4f13-9c82-d24f9290edd7',
}, '#container');
}
render() {
console.log('render is called');
return (
<div id="container"></div>
);
}
The script sometimes takes time to load (generally first time) and when componentDidMount()
is called "foo" is not available and I get an error like this:
TypeError: Cannot read property 'render' of undefined
How can I assure that componentDidMount()
is called once the script is loaded successfully?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…