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;
  • 相关阅读:
    android---eclipse中绑定第三方源代码
    软件安装错误:invalid Drive
    android---获取设备相关信息
    android---获取cpu核心个数
    android---库工程
    eclipse---常用快捷键
    android---adb常用命令
    好用的工具
    “您即将提交的信息不安全”问题处理
    业务系统pdf样式问题01
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9010430.html
Copyright © 2011-2022 走看看