React 16.3 Lifecycle Changes
React 16.3 deprecates the legacy lifecycle methods componentWillMount, componentWillReceiveProps, and componentWillUpdate, replacing them with the static getDerivedStateFromProps API, while also recommending against but explaining the use‑cases for semi‑controlled components that delegate state control to props when supplied and fallback to internal state otherwise.
一、React 16.3 生命周期变更
React 16.3 开始,React 废弃了一些 API(
<span style="display: inline-block; font-size: 15px">componentWillMount</span>、
<span style="display: inline-block; font-size: 15px">componentWillReceiveProps</span>、
<span style="display: inline-block; font-size: 15px">componentWillUpdate</span>),同时推出了一些新的 API 代替,包括
<span style="display: inline-block; font-size: 15px">getDerivedStateFromProps</span>。
根据应用场景的不同,
<span style="display: inline-block; font-size: 15px">getDerivedStateFromProps</span>的使用方式也不同。
一、半受控组件
虽然 React 官方不推荐半受控组件,当然从 API 设计和维护的角度考虑也是不推荐的。但是实际需求往往会出现用户不关心某个业务逻辑的内部实现,但是又希望在有需要的时候能完全控制内部的一些状态,这时候半受控组件是一个比较好的选择。
设计半受控组件的原则就是尽可能把控制权交给用户,即用户传了某个参数,就是用用户的参数;如果用户没有传参数,就是用组件内部的
<span style="display: inline-block; font-size: 15px">state</span>。在过去,这可能有些麻烦:
<ol><li><p><span style="color: rgb(74, 74, 74); display: block; line-height: 22px; font-size: 14px !important"><span style="line-height: 22px; display: block"><code style="display: flex; line-height: 12px; font-size: 10px; font-family: inherit !important"><span style="color: rgb(102, 102, 234); line-height: 20px; font-size: 13px !important">class</span><span style="color: rgb(64, 126, 231); line-height: 20px; font-size: 13px !important">SomeSearchableComponent</span><span style="color: rgb(102, 102, 234); line-height: 20px; font-size: 13px !important">extends</span><span style="color: rgb(64, 126, 231); line-height: 20px; font-size: 13px !important">Component</span><span style="color: rgb(27, 25, 24); line-height: 20px; font-size: 13px !important">{</span></code></span></span></p></li><li><p></p></li></ol>Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Youzan Coder
Official Youzan tech channel, delivering technical insights and occasional daily updates from the Youzan tech team.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
