简体   繁体   中英

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.

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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