Javascript 反应和加载事件

Javascript 反应和加载事件,javascript,jquery,reactjs,Javascript,Jquery,Reactjs,我想在React中实现一个预加载程序 我尝试了以下方法 class MainApp extends React.Component { componentDidMount() { this.preloader.style.display = 'none'; } render() { return ( <div id="loader-container" ref={(c) => { this.preloader = c; }} />

我想在React中实现一个预加载程序

我尝试了以下方法

class MainApp extends React.Component {

  componentDidMount() {
    this.preloader.style.display = 'none';
  }

  render() {
    return (
        <div id="loader-container" ref={(c) => { this.preloader = c; }} />
        <SomeComponent />
    );
  }
}
class MainApp扩展了React.Component{
componentDidMount(){
this.preload.style.display='none';
}
render(){
返回(
{this.preload=c;}}/>
);
}
}
然而,似乎在加载完成之前很久,预加载程序就消失了


如何将预加载程序的删除绑定到加载事件?

我认为问题在于,当您的父组件(MainApp)已加载且请求可能尚未完成时,您正在隐藏加载程序容器

加载完成时,您可以向子组件传递一个要调用的函数,如下所示:

class MainApp extends React.Component {
    constructor (props) {
        super(props);
        this.hideLoader = this.hideLoader.bind(this);
    }

    hideLoader() {
        this.preloader.style.display = 'none';
    }

    render() {
        return (
            <div id="loader-container" ref={(c) => { this.preloader = c; }} />
            <SomeComponent onLoaded={this.hideLoader} />
        );
    }
}
class SomeComponent extends React.Component {
    componentWillMount () {
        fetch(url)
        .then(response => {
            this.setState(...);
            this.props.onLoaded();
        });
     }
}
好吧,我用了

window.addEventListener('load', this.handleLoad);
componentDidMount

似乎能胜任这项工作


谢谢

Hey@kakamg0,为什么您指的是http请求?在我的例子中,SomeComponent是一个常量组件。对不起,当你说预加载程序在加载完成之前很久就消失了时,我想你说的是一个请求。但我看到你已经找到了解决办法。
  handleLoad() {
    $('#loader-container').hide(); //  $ is available here
  }