高階函數 HOF & 高階組件 HOC


高階函數 HOF & 高階組件 HOC

高階類 js HOC

高階函數 HOF

  1. 函數作為參數
  2. 函數作為返回值
"use strict";

/**
 *
 * @author xgqfrms
 * @license MIT
 * @copyright xgqfrms
 * @created 2020-10-01
 * @modified
 *
 * @description 高階函數
 * @difficulty Easy Medium Hard
 * @complexity O(n)
 * @augments
 * @example
 * @link
 * @solutions
 *
 * @best_solutions
 *
 */

const log = console.log;

let count = 0;

const stID = setTimeout(() => {
  log(`setTimeout`, count);
  clearTimeout(stID);
}, 1000);

const siID = setInterval(() => {
  count += 1;
  log(`setInterval`, count);
  if(count >= 3) {
    clearTimeout(siID);
  }
}, 1000);

const arr = [...new Uint8Array(10)].map((item, i) => item = i);

log(`arr =`, arr)

const filter = arr.filter((item, i) => item % 2 === 0);

log(`filter=`, filter)


/*

$ node hof.js

arr = [
  0, 1, 2, 3, 4,
  5, 6, 7, 8, 9
]
filter= [ 0, 2, 4, 6, 8 ]
setTimeout 0
setInterval 1
setInterval 2
setInterval 3


*/


高階組件 HOC

  1. 組件作為參數

  2. 組件作為返回值



component wrapper

高階組件,是一個函數,接受一個組件作為參數,返回一個包裹后的新組件!

匿名 class extends


// This function takes a component...
function withSubscription(WrappedComponent, selectData) {
  // ...and returns another component...
  // return class HOC extends React.Component {
  // ✅❓匿名 class extends
  return class extends React.Component {
    constructor(props) {
      super(props);
      this.handleChange = this.handleChange.bind(this);
      this.state = {
        data: selectData(DataSource, props)
      };
    }

    componentDidMount() {
      // ... that takes care of the subscription...
      DataSource.addChangeListener(this.handleChange);
    }

    componentWillUnmount() {
      DataSource.removeChangeListener(this.handleChange);
    }

    handleChange() {
      this.setState({
        data: selectData(DataSource, this.props)
      });
    }

    render() {
      // ... and renders the wrapped component with the fresh data!
      // Notice that we pass through any additional props
      return <WrappedComponent data={this.state.data} {...this.props} />;
    }
  };
}

Debugging

Wrap the Display Name for Easy Debugging


function withSubscription(WrappedComponent) {
  // ✅ 命名 class extends
  class WithSubscription extends React.Component {/* ... */}
  // 獲取 組件名
  WithSubscription.displayName = `WithSubscription(${getDisplayName(WrappedComponent)})`;
  return WithSubscription;
}

function getDisplayName(WrappedComponent) {
  return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}

import React, { Component } from 'react';

// 獲取組件名
function getDisplayName(WrappedComponent) {
  return WrappedComponent.displayName || WrappedComponent.name || 'HOC Component';
}

// HOC 1. 接收一個組件作為參數
function HOC(WrappedComponent, props) {
  // do something
  const name = WrappedComponent.name || "hoc";
  HOC.displayName = `HOC_${getDisplayName(WrappedComponent)}`;
  // HOC 2. 返回一個新組件
  // ✅ 匿名 class extends (Anonymous)
  // return class extends Component {
  // ✅ 命名 class extends ()
  return class HOC extends Component {
    // constructor(props) {
    //   super();
    // }
    render() {
      return (
        <>
          <WrappedComponent props={props} data={name}/>
        </>
      )
    }
  }
}


export default HOC;

refs

https://reactjs.org/docs/higher-order-components.html



©xgqfrms 2012-2020

www.cnblogs.com 發布文章使用:只允許注冊用戶才可以訪問!



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM