zoukankan      html  css  js  c++  java
  • [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;
  • 相关阅读:
    170325 第六章应用层 域名系统 DNS
    文件操作(Linux系统调用)
    进程优先级,进程nice值和%nice的解释
    常用的操作系统进程调度算法
    fork函数返回值问题
    进度条的实现
    find命令
    单链表的插入排序
    B树
    排序
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9010430.html
Copyright © 2011-2022 走看看