[React] Refactor componentWillReceiveProps() to getDerivedStateFromProps() in React 16.3
The componentWillReceiveProps() method is being deprecated in future version of React (17). Many of us use this method day-to-day to check for incoming prop changes, store state, and to invoke side effects like logging or fetching data from a server.
In this lesson, we'll look at how to refactor an existing component that uses componentWillReceiveProps() to instead use getDerivedStateFromProps() and componentDidUpdate().
Additional Resources: https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#migrating-from-legacy-lifecycles
In short,
componentWillReceiveProps:
The new static
getDerivedStateFromProps
lifecycle is invoked after a component is instantiated as well as when it receives new props. It can return an object to updatestate
, ornull
to indicate that the newprops
do not require anystate
updates.
should handle any local data changes:
static getDerivedStateFromProps(nextProps, prevState) {
const { number } = nextProps; return number === prevState.number
? { computedMessage: "Same number, try again!", number }
: { computedMessage: null, number };
}
componentDidUpdate:
hanlde any async update
componentDidUpdate(nextProps) {
const { number } = nextProps;
if (this.state.computedMessage === null) {
fakeServerRequest(this.props.number).then(result => {
this.setState({ computedMessage: result });
});
}
}
componentWillReceiveProps together with
componentDidUpdate
, this new lifecycle should cover all use cases for the legacycomponentWillReceiveProps
.
最新文章
- C#调用Windows API函数截图
- php/js互传cookie中文乱码的问题
- html5新特性之音频、视频
- SSE技术详解:一种全新的HTML5服务器推送事件技术
- maven 热部署成功案列
- [Express] Level 2: Middleware -- 2
- ASP.NET MVC 4 如何避免数据库被自动创建或自动迁移
- Oracle中存储过程传入表名学习
- “文件XXX正由另一进程使用,因此该进程无法访问此文件”
- WeUI
- ICON图标文件解析
- LCA 学习算法 (最近的共同祖先)poj 1330
- 我从现象中学到的CSS
- js常用内置对象及方法
- Linux ext2文件系统之初步思考
- Mysql根据一个基库生成其他库与其不同的库升级脚本
- javascript之DOM编程设置节点插入节点
- Windows下用python来获取微信撤回消息
- 【LDA】周志华
- Eloquent JavaScript #06# class
热门文章
- Python入门 来点栗子
- Squares(枚举+set 查找)
- 【Luogu4389】付公主的背包
- MySQL-基础操作之增删改查
- Elasticserach 同步索引报错:ElasticSearch ClusterBlockException[blocked by: [FORBIDDEN/12/index read-only / allow delete (api)]
- ubuntu Ngin Install
- git上
- 使用NDK编译VTK
- <;转>;python 发送邮件实例
- 记录:Ubuntu下升级Python从2.x到3.x