首页 > 解决方案 > 反应应用程序更新状态时页面的双重重新加载

问题描述

这是我的应用程序设置的简化版本。这不是确切的代码 - 但应该重现我正在努力解决的不良行为。

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

我想在页面顶部加载事件横幅链接。应用程序加载一次,然后请求完成,设置状态,然后应用程序再次重新加载 - 整个页面刷新 - 这会导致页面闪烁,并且通常是糟糕的用户体验。

有谁知道如何解决这一问题?

标签: reactjsreact-routerreact-router-dom

解决方案


听起来您想在事件完成加载之前避免渲染任何站点(例如主页)以避免由横幅渲染引起的布局变化?例如

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

推荐阅读