Reactjs - Bài 7 - component lifecyle là gì ?

Goal

Hiểu về life cycle của Component

Ví dụ dẫn nhập

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta http-equiv='Content-type' content='text/html; charset=utf-8'>
  5. <title>Basic Example Props</title>
  6. </head>
  7. <body>
  8. <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/react.js"></script>
  9. <script src="https://cdnjs.cloudflare.com/ajax/libs/react/0.13.3/JSXTransformer.js"></script>
  10. <script src="https://cdnjs.cloudflare.com/ajax/libs/superagent/0.15.7/superagent.min.js"></script>
  11. <script type="text/jsx">
  12. var Avatar = React.createClass({
  13. propTypes: {
  14. id: React.PropTypes.string.isRequired,
  15. name: React.PropTypes.string.isRequired,
  16. width: React.PropTypes.number.isRequired,
  17. height: React.PropTypes.number.isRequired,
  18. initialLike: React.PropTypes.bool.isRequired,
  19. // Thêm Interface onDelete()
  20. onDelete: React.PropTypes.func.isRequired,
  21. },
  22. getInitialState() {
  23. return {
  24. liked: this.props.initialLike
  25. };
  26. },
  27. onClick() {
  28. this.setState({liked: !this.state.liked});
  29. },
  30. // Ủy quyền cho Component cha xử lý.
  31. _onDelete() {
  32. this.props.onDelete(this.props.id);
  33. },
  34. render() {
  35. var textLike = this.state.liked ? 'like' : 'haven\'t liked';
  36. return (
  37. <li key={this.props.id}>
  38. <span>{this.props.id}</span>
  39. <img src={this.props.src} width={this.props.width} height={this.props.height} alt="alt" />
  40. <span>{this.props.name}</span>
  41. <button onClick={this.onClick}>{textLike}</button>
  42. <button onClick={this._onDelete}>Delete</button>
  43. </li>
  44. );
  45. }
  46. });
  47. var request = window.superagent;
  48. var Avatars = React.createClass({
  49. getInitialState() {
  50. return {
  51. avatars: [
  52. {id: 1, name: "Avatar 1", height: 100, width: 100, like: false, src: "http://canime.files.wordpress.com/2010/05/mask-dtb.jpg"},
  53. {id: 2, name: "Avatar 2", height: 100, width: 100, like: true, src: "http://z4.ifrm.com/30544/116/0/a3359905/avatar-3359905.jpg"},
  54. {id: 3, name: "Avatar 3", height: 100, width: 100, like: false, src: "http://www.dodaj.rs/f/O/IM/OxPONIh/134.jpg"}
  55. ]
  56. }
  57. },
  58. // Thêm method deleteItem() set lại State (chứa các Component con) cho Component cha này
  59. deleteItem(id) {
  60. this.setState({
  61. avatars: this.state.avatars.filter(function(avatar){
  62. return avatar.id !== id;
  63. })
  64. });
  65. },
  66. componentDidMount: function() {
  67. var self = this;
  68. request.get('http://localhost:3000/api/employees', function(res) {
  69. console.log(res);
  70. self.setState({avatars: res.body});
  71. });
  72. },
  73. render() {
  74. var avatars = this.state.avatars.map(function(avatar){
  75. // use below solution
  76. // map(function(){},this)
  77. // or map(function(){}.bind(this))
  78. // or var that = this; onDelete = {that.deleteUser}
  79. // to pass this value to map function.
  80. // bind onDelete (event) to deleteUser.
  81. return <Avatar onDelete={this.deleteItem} id={avatar.id} name={avatar.name} width={avatar.width} height={avatar.height} src={avatar.src} initialLike={avatar.like} />;
  82. }, this);
  83. return (
  84. <ul>
  85. {avatars}
  86. </ul>
  87. );
  88. }
  89. });
  90. var AvatarsComponent = React.render(<Avatars />, document.body);
  91. </script>
  92. </body>
  93. </html>
Trong ví dụ trên, tôi có đưa thêm vào một method là componentDidMount(). Trong phương thức này tôi sẽ lấy dữ liệu từ server lên và change state của Component là avatars. Method componentDidMount() là nằm trong LifeCycle của Component.
  • Trong ví dụ trên, tôi có dùng:
    1. superagentjs để thay cho jQuery Ajax
    2. loopback để tạo api server.
      (Bạn có thể dùng json server để có thể tạo một Mock API server đơn giản hơn)

Tham khảo

Link dưới đây minh họa khá rõ về Life Cycle của Component. Mời các bạn tham khảo.
http://javascript.tutorialhorizon.com/2014/09/13/execution-sequence-of-a-react-components-lifecycle-methods/