[React] Update State Based on Props using the Lifecycle Hook getDerivedStateFromProps in React16.3

getDerivedStateFromProps is lifecycle hook introduced with React 16.3 and intended as a replacement for componentWillReceiveProps. It is invoked after a component is instantiated as well as when it receives new props. It should return an object to update state, or null to indicate that the new props do not require any state updates.

import React, { Component, Fragment } from "react";

class FetchJson extends Component {
  state = {
    url: null,
    data: null,
    isLoading: true
  };

  static getDerivedStateFromProps(nextProps, prevState) {
    console.log("getDerivedStateFromProps", nextProps);
    if (prevState.url !== nextProps.url) {
      return {
        url: nextProps.url,
        data: null,
        isLoading: true
      };
    }

    return null;
  }

  fetchAndUpdate = async () => {
    const url = this.state.url;
    const response = await fetch(url);
    const result = await response.json();
    this.setState(state => {
      return { data: result, isLoading: false };
    }); 
  };

  componentDidMount() {
    this.fetchAndUpdate();
  }

  componentDidUpdate() {
    if (this.state.isLoading) {
      this.fetchAndUpdate();
    }
  }

  render() {
    return <Fragment>{this.props.render(this.state)}</Fragment>;
  }
}

export default FetchJson;
原文地址:https://www.cnblogs.com/Answer1215/p/9010430.html