Prevent componentDidMount from fetching data if al

2019-07-13 00:23发布

问题:

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