脚本加载反应 [英] Script load in react
问题描述
我想从CDN加载脚本,然后在React中执行该脚本公开的函数:
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>
);
}
脚本有时需要一些时间来加载(通常是第一次)和 componentDidMount()
被称为foo不可用,我收到如下错误:
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:无法读取未定义属性'render'
TypeError: Cannot read property 'render' of undefined
我如何确保 componentDidMount()<脚本加载成功后会调用/ code>吗?
How can I assure that componentDidMount()
is called once the script is loaded successfully?
推荐答案
我认为这不是一个好主意根据反应组件规格和生命周期
I don't think it's a good idea to load scripts in componentWillMount() or componentDidMount(), according to React Component Specs and Lifecycle.
以下代码可以帮助您。
function new_script(src) {
return new Promise(function(resolve, reject){
var script = document.createElement('script');
script.src = src;
script.addEventListener('load', function () {
resolve();
});
script.addEventListener('error', function (e) {
reject(e);
});
document.body.appendChild(script);
})
};
// Promise Interface can ensure load the script only once.
var my_script = new_script('http://example.com/aaa.js');
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
status: 'start'
};
}
do_load = () => {
var self = this;
my_script.then(function() {
self.setState({'status': 'done'});
}).catch(function() {
self.setState({'status': 'error'});
})
}
render() {
var self = this;
if (self.state.status === 'start') {
self.state.status = 'loading';
setTimeout(function () {
self.do_load()
}, 0);
}
return (
<div>{self.state.status} {self.state.status === 'done' && 'here you can use the script loaded'}</div>
);
}
}
这篇关于脚本加载反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!