zoukankan      html  css  js  c++  java
  • 函数节流与函数去抖

    组件通信

    • 父组件向子组件通信:最常用

    父组件通过props向子组件传递参数

    • 子组件向父组件通信:利用回调函数

    父组件将一个函数作为props传递给子组件,子组件调用该回调函数,向父组件通信。

    • 跨级组件之间通信:爷孙通信
    1. 中间组件层层传递props(存在嵌套太深的问题)
    2. 使用context对象(推荐)

    context是全局容器,静态属性,使用条件:

    1. 父组件要声明自己支持context,并提供context中属性的PropTypes
    2. 子组件要声明自己需要使用context,并提供需要使用的context中属性的PropTypes
    3. 父组件需提供一个getChildContext函数,返回一个相应的初始context对象

    若组件中使用constructor函数,务必在构造函数中传入第二个参数context,并在super调用父类构造函数时也传入context,否则会造成组件中无法使用context

    constructor(props,context){
      super(props,context);
    }
    
    • 非嵌套组件间通信:
    1. 利用二者共同父组件的context对象通信(存在嵌套太深、组件耦合度大的问题)
    2. 使用自定义事件的方式(事件订阅,推荐)

    节流

    Throttle,阻止函数在给定时间内被多次调用。

    import throttle from 'lodash.throttle';
    
    class LoadMoreButton extends React.Component {
      constructor(props) {
        super(props);
        this.handleClick = this.handleClick.bind(this);
        this.handleClickThrottled = throttle(this.handleClick, 1000);
      }
    
      componentWillUnmount() {
        this.handleClickThrottled.cancel();
      }
    
      render() {
        return <button onClick={this.handleClickThrottled}>Load More</button>;
      }
    
      handleClick() {
        this.props.loadMore();
      }
    }
    

    防抖

    Debounce,确保函数上次执行后的一段时间内,不会再次执行。

    import debounce from 'lodash.debounce';
    
    class Searchbox extends React.Component {
      constructor(props) {
        super(props);
        this.handleChange = this.handleChange.bind(this);
        this.emitChangeDebounced = debounce(this.emitChange, 250);
      }
    
      componentWillUnmount() {
        this.emitChangeDebounced.cancel();
      }
    
      render() {
        return (
          <input
            type="text"
            onChange={this.handleChange}
            placeholder="Search..."
            defaultValue={this.props.value}
          />
        );
      }
    
      handleChange(e) {
        // React pools events, so we read the value before debounce.
        // Alternately we could call `event.persist()` and pass the entire event.
        // For more info see reactjs.org/docs/events.html#event-pooling
        this.emitChangeDebounced(e.target.value);
      }
    
      emitChange(value) {
        this.props.onChange(value);
      }
    }
    

    参考

    组件通信 - 在组件中使用事件处理函数

  • 相关阅读:
    eclipse export runnable jar(导出可执行jar包) runnable jar可以执行的
    mave常用指令
    771. Jewels and Stones珠宝数组和石头数组中的字母对应
    624. Maximum Distance in Arrays二重数组中的最大差值距离
    724. Find Pivot Index 找到中轴下标
    605. Can Place Flowers零一间隔种花
    581. Shortest Unsorted Continuous Subarray连续数组中的递增异常情况
    747. Largest Number At Least Twice of Others比所有数字都大两倍的最大数
    643. Maximum Average Subarray I 最大子数组的平均值
    414. Third Maximum Number数组中第三大的数字
  • 原文地址:https://www.cnblogs.com/wjcx-sqh/p/9219825.html
Copyright © 2011-2022 走看看