如果已从服务器端可用,则防止 componentDidMount 获取数据

IT技术 javascript reactjs redux react-redux
2021-05-11 21:22:55

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

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

  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 })
      })
    }
  }
2个回答

我找到了一个替代解决方案。在我的 Redux 商店中,我保留了当前页面的 URL。因此,在导航上,我可以执行以下操作:

componentDidMount() {
  const { url, match } = this.props;
  if (url !== match.url) {
    fetchData(match.path);
  }
}

只需在商店中使用一个布尔变量,我只使用一个名为“完成”的变量,当服务器获取数据时,它会将变量设置为 true,在 componentDidMount 中的组件中只检查变量是否为 true,如果为,则不要获取数据,像这样:

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