【问题标题】:ReactJS - Loading Indicator Not DisappearingReactJS - 加载指示器没有消失
【发布时间】:2018-03-01 00:56:10
【问题描述】:

我有一个加载指示器,我希望在加载页面时出现,但在安装组件后消失。起初我试图通过在componentDidMount(){} 中使用this.setState(isLoading: false); 来删除指示器,但这会引发警告。相反,我把它放在componentWillUnmount(){} 中,这使得指示器可见,但是一旦我的组件被加载,它就永远不会消失。我是否将状态设置在错误的位置?有更好的路线吗?

一旦出现<BlogFeed/>,我基本上希望隐藏<LoadingIndicator/>

class BlogFeedContainer extends React.Component{
    constructor(props, context) {
        super(props, context);
        this.state = this.context.data || window.__INITIAL_STATE__ || {blogs: [], isLoading: true};
    }

    fetchList() {
....
}

componentWillUnmount(){
        this.setState(isLoading: false);
    }

    componentDidMount() {
        this.fetchList();
    }

    render() {
        return (
            <div className="container">
                <LoadingIndicator loading={this.state.isLoading} />
                <BlogFeed {...this.state} />
            </div>
        )
    }

//Loading Indicator
const LoadingIndicator = props => {
    if(props.loading){
        return (
            <div class="spinner">
              <div class="bounce1"></div>
              <div class="bounce2"></div>
              <div class="bounce3"></div>
              <p>Loading...</p>
            </div>
        )
    } else {
        return;
    }
}

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    this.setState(isLoading: false); 不是有效的 JavaScript。请改用functional setState

    this.setState(() => ({ isLoading: false }));
    

    【讨论】:

    • this.setState({isLoading: false}) 在这种情况下就足够了。仅当需要根据当前状态计算下一个状态时才需要使用函数,该状态可能已被先前的setState() 调用更改。这是因为对 setState() 的多次调用是批处理的,否则会覆盖以前的调用。
    • 这两种方法都对我有用,但是一旦出现&lt;BlogFeed /&gt; 组件,您的建议似乎并没有删除指示器
    猜你喜欢
    • 1970-01-01
    • 2020-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    • 2019-12-30
    • 1970-01-01
    相关资源
    最近更新 更多