Guest User

Untitled

a guest
Dec 15th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.18 KB | None | 0 0
  1. import React from 'react';
  2.  
  3. class Effect extends React.Component {
  4. componentDidMount() {
  5. this.previous = this.props.onRender();
  6. }
  7. componentDidUpdate(prevProps) {
  8. console.log('cdu');
  9. if (
  10. prevProps.cache &&
  11. this.props.cache &&
  12. prevProps.cache.length === this.props.cache.length &&
  13. prevProps.cache.every((prop, index) => {
  14. return prop === this.props.cache[index];
  15. })
  16. ) {
  17. return;
  18. }
  19. this.clearPrevious();
  20. this.previous = this.props.onRender();
  21. }
  22. componentWillUnmount() {
  23. this.clearPrevious();
  24. }
  25. clearPrevious() {
  26. if (typeof this.previous === 'function') {
  27. this.previous();
  28. }
  29. }
  30. render() {
  31. return null;
  32. }
  33. }
  34.  
  35. class State extends React.Component {
  36. constructor(props) {
  37. super(props);
  38. this.state = {
  39. value: props.initial,
  40. };
  41. this.childSetState = update => {
  42. const updator = typeof update === 'function' ? update : () => update;
  43. this.setState(state => ({ value: updator(state.value) }));
  44. }
  45. }
  46. render() {
  47. return (this.props.children || this.props.render)(this.state.value, this.childSetState);
  48. }
  49. }
  50.  
  51. const UsingComponents = () => {
  52. return (
  53. <State initial={5} >
  54. {(count, setCount) => (
  55. <span>
  56. <Effect
  57. onRender={() => {
  58. const timeout = setTimeout(() => {
  59. setCount(0);
  60. }, 2000);
  61. return () => {
  62. clearTimeout(timeout);
  63. }
  64. }}
  65. cache={[count > 10]}
  66. />
  67. Count: {count} <button type="button" onClick={() => setCount(count => count + 1)}>Inc</button>
  68. </span>
  69. )}
  70. </State>
  71. );
  72. };
  73.  
  74. const UsingHooks = () => {
  75. const [count, setCount] = React.useState(5);
  76. React.useEffect(() => {
  77. const timeout = setTimeout(() => {
  78. setCount(0);
  79. }, 2000);
  80. return () => {
  81. clearTimeout(timeout);
  82. }
  83. }, [count > 10]);
  84. return (
  85. <span>
  86. Count: {count} <button type="button" onClick={() => setCount(count => count + 1)}>Inc</button>
  87. </span>
  88. );
  89. };
  90.  
  91. export default () => (
  92. <>
  93. <h4>Using Components</h4>
  94. <UsingComponents />
  95. <h4>Using Hooks</h4>
  96. <UsingHooks />
  97. </>
  98. );
Add Comment
Please, Sign In to add comment