最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - React and on load event - Stack Overflow

programmeradmin2浏览0评论

I'm trying to implement a pre-loader in React,

I tried the following

class MainApp extends React.Component {

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

  render() {
    return (
        <div id="loader-container" ref={(c) => { this.preloader = c; }} />
        <SomeComponent />
    );
  }
}

However, it seems that the pre-loader disapper long before the load is plete.

How can I bind the removal of the pre-loader to the load event?

I'm trying to implement a pre-loader in React,

I tried the following

class MainApp extends React.Component {

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

  render() {
    return (
        <div id="loader-container" ref={(c) => { this.preloader = c; }} />
        <SomeComponent />
    );
  }
}

However, it seems that the pre-loader disapper long before the load is plete.

How can I bind the removal of the pre-loader to the load event?

Share Improve this question asked Oct 20, 2017 at 5:02 Liron TovalLiron Toval 891 gold badge1 silver badge8 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 1

Ok so I used

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

In ponentDidMount

and

  handleLoad() {
    $('#loader-container').hide(); //  $ is available here
  }

seems to do the job

Thanks

I think the problem is that you're hiding the loader container when your parent ponent (MainApp) is mounted and the request probably is not finished yet.

You could pass to the child ponent a function to call when the load is pleted like this:

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} />
        );
    }
}

And in SomeComponent you should call this.props.onLoaded() when the request is finished. Something like this:

class SomeComponent extends React.Component {
    ponentWillMount () {
        fetch(url)
        .then(response => {
            this.setState(...);
            this.props.onLoaded();
        });
     }
}
发布评论

评论列表(0)

  1. 暂无评论