likes
comments
collection
share

react 学习总结(一)

作者站长头像
站长
· 阅读数 20

标签<React.StrictMode>

注意:严格模式检查仅在开发模式下运行;它们不会影响生产构建。

StrictMode 目前有助于:1、识别不安全的生命周期2、关于使用过时字符串 ref API 的警告3、关于使用废弃的 findDOMNode 方法的警告4、检测意外的副作用5、检测过时的 context API

生命周期警告过时的组件生命周期往往会带来不安全的编码实践,具体函数如下:

1、componentWillMount2、componentWillReceiveProps3、componentWillUpdate

16.3:为不安全的生命周期引入别名

1、UNSAFE_componentWillMount2、UNSAFE_componentWillReceiveProps3、UNSAFE_componentWillUpdate

ref API 的警告参考地址:https://wuqiang.blog.csdn.net/article/details/104153645

检测副作用渲染阶段的生命周期包括以下 class 组件方法:

1、constructor2、componentWillMount (or UNSAFE_componentWillMount)3、componentWillReceiveProps (or UNSAFE_componentWillReceiveProps)4、componentWillUpdate (or UNSAFE_componentWillUpdate)5、getDerivedStateFromProps6、shouldComponentUpdate7、render8、setState 更新函数(第一个参数)

因为上述方法可能会被多次调用,所以不要在它们内部编写副作用相关的代码,这点非常重要。忽略此规则可能会导致各种问题的产生,包括内存泄漏和或出现无效的应用程序状态。不幸的是,这些问题很难被发现,因为它们通常具有非确定性。

严格模式不能自动检测到你的副作用,但它可以帮助你发现它们,使它们更具确定性。通过故意重复调用以下函数来实现的该操作:

1、class 组件的 constructor,render 以及 shouldComponentUpdate 方法2、class 组件的生命周期方法 getDerivedStateFromProps3、函数组件体4、状态更新函数 (即 setState 的第一个参数)5、函数组件通过使用 useState,useMemo 或者 useReducer

context API 警告

context API 警告过时的 context API 容易出错,将在未来的主要版本中删除。在所有 16.x 版本中它仍然有效,但在严格模式下,将显示以下警告:

参考文档