首页 > 解决方案 > React - 在呈现获取的数据之前显示加载消息

问题描述

我正在尝试构建一个与服务器通信以从数据库中查询数据的反应应用程序。我想在应用程序获取数据时显示加载消息。这是代码片段:

class App extends React.Component {
    constructor(props) {
        super(props)

        this.clickHandler = this.clickHandler.bind(this); 

        this.state = {
            isLoading: false, 
            data: [], 
            content: ''
        }
    }

    clickHandler() {
        this.setState({ isLoading: true }); 
        fetch('url_1')
          .then(res => res.json())
          .then(data => this.setState({ data: data }, () => {
            this.getContentByData() // loading message vanished before content is displayed
          }))
          .then(() => this.setState({ isLoading: false }));
    }

    getContentByData() {
        fetch(`url_2?data=${this.state.data}`)
        .then(res => res.json())
        .then(content => this.setState({ content: content }))
    }

    render() {
        return (
            <div>
                {this.state.isLoading ? <h1>loading</h1>: null}
                <h6>{this.state.content}</h6>
                <button type="button" onClick={this.clickHandler}>Click Me!</button>
            </div>
        )
    }
}

ReactDOM.render(<App />, document.getElementById('app'))

加载消息在显示内容之前消失。我怎样才能解决这个问题?

标签: reactjs

解决方案


你可以改变你的render方法是这样的:

render() {
    let content = <Loader />;
    if (!this.state.isLoading && this.state.content) {
       content = (
           <h6>{this.state.content}</h6>
           <button type="button" onClick={this.clickHandler}>Click Me!</button>
       )
    }
        return (
        <div>
            {content}
        </div>
    )
}

Loader您的加载程序组件在哪里。当然它也可以是 h1 标题或任何你想要的。


推荐阅读