title: 组件生命周期

生命周期

react 提供了一个完善的生命周期机制,而在日常业务开发中,我们往往可以借助如 componentDidMount (组件挂载) 进行如 “数据拉取”, componentWillUnmount (组件卸载) 进行如事件销毁等操作。 目前 AMS 也提供致敬 react 2个生命周期:

componentDidMount componentWillUnmount

最佳实践:请尽可能在页面顶层使用生命周期进行如异步请求的操作, 这将有利于组件状态之间的管理

组件挂载/组件卸载

在组件初始化完并渲染到页面时,componentDidMount 将被执行。以下为基本用法:

  1. class Card extends React.Component {
  2. componentDidMount() {
  3. // ...
  4. }
  5. componentWillUnmount() {
  6. // ...
  7. }
  8. render() {
  9. // ...
  10. }
  11. }
  1. {
  2. "$$$": "component",
  3. "registryName": "antd",
  4. "componentName": "Card",
  5. "lifecycle": {
  6. "componentDidMount": {
  7. // ...
  8. },
  9. "componentWillUnmount": {
  10. // ...
  11. }
  12. },
  13. "props": {
  14. // ...
  15. }
  16. }

实战用例: 在组件加载时获取用户信息,在组件卸载时加入埋点统计。

  1. {
  2. "$$$": "component",
  3. "registryName": "html",
  4. "componentName": "div",
  5. "lifecycle": {
  6. "componentDidMount": {
  7. "$$$": "function",
  8. "registryName": "base",
  9. "componentName": "ajax",
  10. "args": [
  11. {
  12. "url": "//xxx.com/api/get-user-info-by-id",
  13. "method": "get",
  14. "params": {
  15. "userId": "aa6d7719-1914-4ad0-96a0-5b500ad6426c"
  16. }
  17. }
  18. ]
  19. },
  20. "componentWillUnmount": {
  21. "$$$": "function",
  22. "registryName": "base",
  23. "componentName": "ajax",
  24. "args": [
  25. {
  26. "url": "//xxx.com/api/track",
  27. "method": "get"
  28. }
  29. ]
  30. }
  31. },
  32. "props": {
  33. // ...
  34. }
  35. }