当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 深入理解React高阶组件

深入理解React高阶组件

2017年12月12日  | 移动技术网IT编程  | 我要评论

1.在react中higher-order component (hoc)是一种重用组件逻辑的高级技术。hoc不是react api中的一部分。hoc是一个函数,该函数接收一个组件并且返回一个新组件。在react中,组件是代码复用的基本单位。

2.为了解释hocs,举下面两个例子

commentlist组件会渲染出一个comments列表,列表中的数据来自于外部。

class commentlist extends react.component {

  constructor() {

   super();

   this.handlechange = this.handlechange.bind(this);

   this.state = {

    // "datasource" is some global data source

    comments: datasource.getcomments()

   };

  }

 

  componentdidmount() {

   // subscribe to changes

   datasource.addchangelistener(this.handlechange);

  }

 

  componentwillunmount() {

   // clean up listener

   datasource.removechangelistener(this.handlechange);

  }

 

  handlechange() {

   // update component state whenever the data source changes

   this.setstate({

    comments: datasource.getcomments()

   });

  }

 

  render() {

   return (

    <div>

     {this.state.comments.map((comment) => (

      <comment comment={comment} key={comment.id} />

     ))}

    </div>

   );

  }

 } 

 接下来是blogpost组件,这个组件用于展示一篇博客信息

class blogpost extends react.component {

  constructor(props) {

   super(props);

   this.handlechange = this.handlechange.bind(this);

   this.state = {

    blogpost: datasource.getblogpost(props.id)

   };

  }

 

  componentdidmount() {

   datasource.addchangelistener(this.handlechange);

  }

 

  componentwillunmount() {

   datasource.removechangelistener(this.handlechange);

  }

 

  handlechange() {

   this.setstate({

    blogpost: datasource.getblogpost(this.props.id)

   });

  }

 

  render() {

   return <textblock text={this.state.blogpost} />;

  }

 } 

这两个组件是不一样的,它们调用了datasource的不同方法,并且它们的输出也不一样,但是它们中的大部分实现是一样的:

1.装载完成后,给datasource添加了一个change listener
2.当数据源发生变化后,在监听器内部调用setstate
3.卸载之后,移除change listener

可以想象在大型应用中,相同模式的访问datasource和调用setstate会一次又一次的发生。我们希望抽象这个过程,从而让我们只在一个地方定义这个逻辑,然后在多个组件中共享。

接下来我们写一个创建组件的函数,这个函数接受两个参数,其中一个参数是组件,另一个参数是函数。下面调用withsubscription函数

const commentlistwithsubscription = withsubscription(

 commentlist,

 (datasource) => datasource.getcomments()

);

 

const blogpostwithsubscription = withsubscription(

 blogpost,

 (datasource, props) => datasource.getblogpost(props.id)

); 

调用withsubscription传的第一个参数是wrapped 组件,第二个参数是一个函数,该函数用于检索数据。

当commentlistwithsubscription和blogpostwithsubscription被渲染,commentlist和blogpost会接受一个叫做data的prop,data中保存了当前从datasource中检索出的数据。withsubscription代码如下:

// this function takes a component...

function withsubscription(wrappedcomponent, selectdata) {

 // ...and returns another component...

 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} />;

  }

 };

} 

 hoc并没有修改输入的组件,也没有使用继承去重用它的行为。hoc只是一个函数。wrapped 组件接受了容器的所以props,同时还接受了一个新的prop(data),data用于渲染wrapped 组件的输出。hoc不关心数据怎么使用也不关心数据为什么使用,wrapped组件不关心数据是哪儿得到。

因为withsubscription只是一个常规的函数,你能添加任意个数的参数。例如,你能让data prop的名字是可配置的,从而进一步将hoc与wrapped组件隔离。

或者接受一个配置shouldcomponentupdate,或者配置数据源的参数

使用高阶组件时有些需要注意的地方。

1.不要修改原始组件,这一点很重要

有如下例子:

function logprops(inputcomponent) {

 inputcomponent.prototype.componentwillreceiveprops = function(nextprops) {

  console.log('current props: ', this.props);

  console.log('next props: ', nextprops);

 };

 // the fact that we're returning the original input is a hint that it has

 // been mutated.

 return inputcomponent;

}

 

// enhancedcomponent will log whenever props are received

const enhancedcomponent = logprops(inputcomponent); 

这里存在一些问题,1.输入的组件不能与增强的组件单独重用。2.如果给enhancedcomponent应用其他的hoc,也会改变componentwillreceiveprops。

这个hoc对函数类型的组件不适用,因为函数类型组件没有生命周期函数hoc应该使用合成代替修改——通过将输入的组件包裹到容器组件中。

function logprops(wrappedcomponent) {

 return class extends react.component {

  componentwillreceiveprops(nextprops) {

   console.log('current props: ', this.props);

   console.log('next props: ', nextprops);

  }

  render() {

   // wraps the input component in a container, without mutating it. good!

   return <wrappedcomponent {...this.props} />;

  }

 }

} 

这个新的logprops与旧的logprops有相同的功能,同时新的logprops避免了潜在的冲突。对class类型的组件和函数类型额组件同样适用。

2.不要在render方法中使用hocs

react的diff算法使用组件的身份去决定是应该更新已存在的子树还是拆除旧的子树并装载一个新的,如果从render方法中返回的组件与之前渲染的组件恒等(===),那么react会通过diff算法更新之前渲染的组件,如果不相等,之前渲染的子树会完全卸载。 

render() {

 // a new version of enhancedcomponent is created on every render

 // enhancedcomponent1 !== enhancedcomponent2

 const enhancedcomponent = enhance(mycomponent);

 // that causes the entire subtree to unmount/remount each time!

 return <enhancedcomponent />;

} 

 在组件定义的外部使用hocs,以至于结果组件只被创建一次。在少数情况下,你需要动态的应用hocs,你该在生命周期函数或者构造函数中做这件事

3.静态方法必须手动复制

有的时候在react组件上定义静态方法是非常有用的。当你给某个组件应用hocs,虽然原始组件被包裹在容器组件里,但是返回的新组件不会有任何原始组件的静态方法。

// define a static method

wrappedcomponent.staticmethod = function() {/*...*/}

// now apply an hoc

const enhancedcomponent = enhance(wrappedcomponent);

 

// the enhanced component has no static method

typeof enhancedcomponent.staticmethod === 'undefined' // true 

 为了让返回的组件有原始组件的静态方法,就要在函数内部将原始组件的静态方法复制给新的组件。

function enhance(wrappedcomponent) {

 class enhance extends react.component {/*...*/}

 // must know exactly which method(s) to copy :(

  // 你也能够借助第三方工具

 enhance.staticmethod = wrappedcomponent.staticmethod;

 return enhance;

} 

 4.容器组件上的ref不会传递给wrapped component

虽然容器组件上的props可以很简单的传递给wrapped component,但是容器组件上的ref不会传递到wrapped component。如果你给通过hocs返回的组件设置了ref,这个ref引用的是最外层容器组件,而非wrapped 组件

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网