reactjs - 反应应用程序更新状态时页面的双重重新加载
问题描述
这是我的应用程序设置的简化版本。这不是确切的代码 - 但应该重现我正在努力解决的不良行为。
class App {
state = { incidents: null };
componentDidMount() {
API.getIncidents().then(incidents => this.setState(incidents));
}
render() {
return (
<>
{this.state.incidents && <IncidentBanner />}
<Switch>
<Route exact path="/" component={Home} />
</Switch>
)
</>
);
}
}
我想在页面顶部加载事件横幅链接。应用程序加载一次,然后请求完成,设置状态,然后应用程序再次重新加载 - 整个页面刷新 - 这会导致页面闪烁,并且通常是糟糕的用户体验。
有谁知道如何解决这一问题?
解决方案
听起来您想在事件完成加载之前避免渲染任何站点(例如主页)以避免由横幅渲染引起的布局变化?例如
class App {
state = { incidents: null, loading: true };
componentDidMount() {
API.getIncidents()
.then(data => this.setState({ incidents: data.incidents, loading: false }))
.catch(() => this.setState({ loading: false }));
}
render() {
if (this.state.loading) {
return null;
}
return (
<>
{this.state.incidents && <IncidentBanner />}
<Switch>
<Route exact path="/" component={Home} />
</Switch>
)
</>
);
}
}
推荐阅读
- arduino - Esp32 摇杆鼠标
- python - 在 Python 中通过 Selenium 抓取 Google 地图
- python-3.x - VScode - Linux 风格的“信息/帮助”命令扩展
- c# - 如何在统一 c# 中切换?
- python-3.x - 环境变量适用于 Django 的服务器,但不适用于 Apache 服务器
- oracle - 如何使用没有连接的联合合并 3 个表?
- javascript - Vuejs 通过使用计算工作,但不能使用 heroku 上的数据工作
- sorting - DynamoDB BETWEEN 排序键与范围
- python - 如何在 Python 中将 uint256 转换为 uint80 以读取智能合约数据?
- mysql - 如何根据来自另一列的不同值从一列中获取值?