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