简体   繁体   English

不鼓励在React中使用HOC吗?

[英]Is this discouraged for HOC in React?

Have some data in component state, that is mapped over like: 有一些处于组件状态的数据,这些数据被映射为:

  render() {
    return (
      <div className="App">
        {this.state.items.map(item => {
            const enhancer = item.color = 'red' ? EnhancerA : EnhancerB
            const Enhanced = withEnhancement(enhancer)
            return <Enhanced {...item} />
          })}
      </div>
    )
  }

withEnhancement is a HoC that takes either EnhancerA or EnhancerB and returns a new component. withEnhancement是一个HoC ,它使用EnhancerAEnhancerB并返回一个新组件。

Would this be bad practice according to the React docs over dont use hocs inside the render method or would this be alright, as doing it inside the return statement? 根据React docs的说法,这是不好的做法吗, 不要在render方法内使用hocs,或者像在return语句内那样使用hocs吗?

I'd say it's pretty bad, yes... But there's a very simple workaround. 我会说这很糟糕,是的。但是有一个非常简单的解决方法。

Put this code BEFORE the class declaration: 将此代码放在类声明之前:

const EnhancedA = withEnhancement(EnhancerA);
const EnhancedB = withEnhancement(EnhancerB);

and inside your render function, choose which enhanced component to use: 在渲染功能中,选择要使用的增强组件:

const Component = item.color = 'red' ? EnhancedA : EnhancedB;
return <Component {...item} />;

The point of this being, you're only creating the "enhanced components" once, and reusing them inside of your map function, instead of creating a new component instance for every new element on your array. 关键是,您只需创建一次“增强组件”,然后在map函数中重新使用它们,而不是为数组中的每个新元素创建一个新的组件实例。

Yes, it would be bad. 是的,那将是不好的。

For the sake of what's discussed in the React docs you linked, they're the same thing, and this would also cause unnecessary forced rerenders. 为了使您链接的React文档中讨论的内容相同,它们是同一回事,这也将导致不必要的强制转售。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM