如果已从服务器端可用,则防止 componentDidMount 获取数据 [英] Prevent componentDidMount from fetching data if already available from server-side

查看:27
本文介绍了如果已从服务器端可用,则防止 componentDidMount 获取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ComponentDidMount() 在组件被挂载时触发,包括在服务器端渲染之后被水合时.

ComponentDidMount() is triggered when the component is mounted, including when it is hydrated following server-side rendering.

我在网上找到的解决方案之一是检查我们是否有状态数据;然而,这需要在每个组件上包含大量代码.还有哪些解决方案?

One of the solutions I found online is checking whether we have data in the state; however this requires a lot of code to include on every component. What are other solutions?

  componentDidMount() {
    // if rendered initially, we already have data from the server
    // but when navigated to in the client, we need to fetch
    if (!this.state.data) {
      this.constructor.fetchData(this.props.match).then(data => {
        this.setState({ data })
      })
    }
  }

推荐答案

只在 store 中使用一个布尔变量,我只使用一个叫做done"的,当服务器获取数据时它设置变量为 true,在componentDidMount 中的组件只是检查变量是否为真,如果是,则不获取数据,如下所示:

Just use a boolean variable in the store, I just use one called "done", when the server fetch the data it set the variable to true, in the component in compoponentDidMount just check if the variable is true, if is, then dont fetch the data, like this:

componentDidMount() {
  if(!this.props.done)
    this.props.fetchData();
}

这篇关于如果已从服务器端可用,则防止 componentDidMount 获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆