react

react 高阶组件结合Context Api(二)

2019-03-15  本文已影响0人  你的时间非常值钱

上集 讲到上手了Context API来解决props drilling问题,下文就讲解如何利用高阶组件(HOC)复用Context,使其能多个地方使用这好玩的特性

// contextHOC.js
// 用属性代理的方法造高阶组件
const Provider = ({Provider},store={}) => Wrappedcomponent => {
  return class extends Component {
    state = store
    // 顶层修改state方法
    updateState = state => setState(state)
    render() {
      return (
        <Provider
          value={{
            ...state,
            updateState: this.updateState, // 消费者调用props.context.updateState就能修改顶层state
          }}
        >
          <Wrappedcomponent  {...this.props} />
        </Provider>
      )
    }
  }
}

const Consumer = ({Consumer}) => Wrappedcomponent => {
  return class extends Component {
    render() {
      return (
        <Consumer>
         {
            // context注入props里
            data => <Wrappedcomponent context={{...data}}  {...this.props} />
          }
        </Consumer>
      )
    }
  }
}

// 导出
export defalut {
  Provider,
  Consumer,
}

// index.js(只展示核心代码,从上到下顺序)
// 干净的组件A,B1,B2
class A extends Component {
  render() {
    return (
      <div style={{ background: "gray" }}>
        <p>父组件</p>
        <B1 />
        <B2 />
      </div>
    );
  }
}
// 子组件1 ConsumerC1由高阶组件和组件C1生成的,需往下看
class B1 extends Component {
  render() {
    return (
      <div style={{ background: "yellow", width: "400px" }}>
        <p>子组件1</p>
        <ConsumerC1 />
      </div>
    );
  }
}
// 子组件2 ConsumerC2由高阶组件和组件C2生成的,需往下看
class B2 extends Component {
  render() {
    return (
      <div style={{ background: "yellow", width: "400px" }}>
        <p>子组件2</p>
        <ConsumerC2 />
      </div>
    );
  }
}
// 孙组件1
class C1 extends Component {
  handleClick = () => {
    const { updateState, num } = this.props.context;
    updateState({
      num: num + 1
    });
  };
  render() {
    console.log("c1 render");
    return (
      <div style={{ background: "white", width: "200px" }}>
        <p>孙组件1</p>
        <button onClick={this.handleClick}>点我</button>
      </div>
    );
  }
}

// 孙组件2
class C2 extends Component {
  render() {
    const { num } = this.props.context;
    console.log("c2 render");
    return (
      <div style={{ background: "pink", width: "200px" }}>
        <p>孙组件2</p>
        <p>num:{num}</p>
      </div>
    );
  }
}

const ProviderA = ContextHOC.Provider(AppContext, { num: 0 })(A);
const ConsumerC1 = ContextHOC.Consumer(AppContext)(C1);
const ConsumerC2 = ContextHOC.Consumer(AppContext)(C2);
// 这里用函数的方法生成高阶组件,其实使用时可以利用es7的decorator修饰器功能,因为在线代码编辑的网站不知怎么配置修饰器语法

// @ContextHOC.Provider(AppContext,{num:0})
// class A extends Component {}
//...
// @ContextHOC.Consumer(AppContext)
// class C1 extends Component {}
// ...
// 语义性更好的@connect()写法
// ...
// ...

然而发现点击按钮时,两个消费者C1,C2同时re-render,理想情况是C1不触发重新渲染,这是什么原因造成呢?

控制台发现多余的re-render

本文案例在线代码

上一篇 下一篇

猜你喜欢

热点阅读