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;
  • 相关阅读:
    状态模式
    简单密码再次加密
    服务层定义自己的服务异常类
    必备网络基础知识(持续补充)
    MongoDB基础入门
    Git命令整理
    算法基础(四)
    RabbitMQ消息队列
    设计模式(23种)
    二叉树知识点
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9010430.html
Copyright © 2011-2022 走看看