Prevent componentDidMount from fetching data if already available from server-side

有些话、适合烂在心里 提交于 2019-12-14 01:46:18

问题


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

回答1:


I have found an alternative solution. In my Redux store I keep the URL of the current page. Therefore on navigation, I am able to do the following:

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



回答2:


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


来源:https://stackoverflow.com/questions/47015661/prevent-componentdidmount-from-fetching-data-if-already-available-from-server-si

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!