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;

最新文章

  1. PHP钩子机制
  2. 小技巧,如何在Label中显示图片
  3. 添加JavaScrip
  4. 怎么使用jquery判断一个元素是否含有一个指定的类(class)
  5. JavaWeb学习----JSTL标签库
  6. Elsevier 投稿各种状态总结
  7. Qt多线程学习:创建多线程
  8. 1.linux下Kconfig编写规范
  9. 把测试app打包成ipa文件
  10. Java运行环境的配置(JDK和JRE)
  11. C#正则怎么判断字符串中是否有汉字
  12. 认识javascript范围和作用域链
  13. Docx组件读写Word文档介绍
  14. 基于Jquery+Ajax+Json+存储过程 高效分页
  15. python中文编码坑
  16. Android 进阶 教你打造 Android 中的 IOC 框架 【ViewInject】 (下)
  17. 【js】前端 js/jquery 常用代码和实践
  18. 使用Sublime Text搭建python调试环境[转]
  19. P1033自由落体
  20. 主机网络ping: unknown host baidu.com问题解决

热门文章

  1. LA4122
  2. hihoCoder 1033
  3. Java同步容器总结
  4. MyEclipse配置https
  5. 禁止tomcat扫描jar包的tld文件
  6. C#微信公众号的开发——服务配置
  7. Hibernate多表映射(三)
  8. 自学Python九 爬虫实战二(美图福利)
  9. 使用IDEA 搭建一个SpringBoot + Hibernate + Gradle
  10. 【Oracle】append