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;
  • 相关阅读:
    dtclog
    求助解决 SQL SERVER 2005 log 事务日志增长太快的问题
    开辟第二战场
    c# 排序 求助
    怎样玩转3D
    爬楼梯问题迭代算法解!
    C++中类的继承方式的区别以及private public protected 范围
    想转c++
    PHP相关笔记
    常用快捷键
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9010430.html
Copyright © 2011-2022 走看看