reactjs - 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'))
加载消息在显示内容之前消失。我怎样才能解决这个问题?
解决方案
你可以改变你的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 标题或任何你想要的。
推荐阅读
- authentication - 有没有办法让一个 Apps 脚本调用另一个,但在不同用户的上下文中?
- jquery - React.JS 组件中的 BxSlider
- json - 在 Wordpress 中创建页面时修复错误后的后果
- python - 我可以输入一个只能输入带空格的名称的变量吗?
- merge - 如何在visio中组合2个框(不分组)
- xml - 从 XML Altova XMLSPY 生成 SQL 表
- r - 从R中的csv文件中提取行
- r - 使用 purrr:pmap_dbl 计算多列的每一行的平均值(数量事先不知道)
- python - 如何在 Chrome 中使用 Selenium 和 python 来检查“重新加载页面”?警告并单击重新加载?
- ruby - FXRuby Fox::FXText 在线程追加时中断