Abh*_*eet 8 javascript reactjs react-redux
我想从CDN加载脚本,然后在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>
);
}
Run Code Online (Sandbox Code Playgroud)
脚本有时需要花时间加载(通常是第一次),什么时候componentDidMount()被称为"foo"不可用,我得到这样的错误:
TypeError:无法读取未定义的属性'render'
如何componentDidMount()在脚本成功加载后确保调用?
小智 17
根据React组件规范和生命周期,我不认为在componentWillMount()或componentDidMount()中加载脚本是个好主意.
以下代码可能对您有所帮助.
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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17248 次 |
| 最近记录: |