首页 > 解决方案 > React - “不要在组件的渲染方法中使用 HOC”是什么意思。访问组件定义之外的 HOC。'?

问题描述

我正在学习 HOC 并继续阅读上面的引用,但我不明白它的含义。如果我的 HOC 向我的消费组件添加了一个方法,我可以像这样在渲染方法中使用该方法吗?如果不是,我将如何做我在这里尝试做的事情:

import React, { Component } from 'react';
import { withMyHOC } from '../with_my_component'

class MyComponent extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    const { methodFromHOC }= this.props;
    const result = methodFromHOC(someArgument);

    return (
      <div >
        {result}
      </div>
    )
  }
}

export default withMyHOC(MyComponent );

标签: reactjshigher-order-components

解决方案


当你说不要在 render 方法中使用 HOC 时,这意味着你不应该在另一个组件的 render 方法中创建被 HOC 包装的组件的实例。例如,如果你有一个使用 MyComponent 的 App 组件,它不应该像下面这样

import React, { Component } from 'react';

class MyComponent extends Component {
  constructor(props) {
    super(props);
  }

  render() {
    const { methodFromHOC }= this.props;
    const result = methodFromHOC(someArgument);

    return (
      <div >
        {result}
      </div>
    )
  }
}

export default MyComponent;

import { withMyHOC } from '../with_my_component'
export default class App extends React.Component {
   render() {
      const Wrap = withMyHOC(MyComponent);
      return (
        <div>
            {/* Other Code */}
            <Wrap />
        </div>
      )
   }
}

为什么你不应该像上面那样使用它是因为每次调用渲染方法时MyComponent都会创建一个由 HOC 包装的新实例,Wrap因此每次它都会被再次挂载而不是通过自然生命周期或 React。

但是,如果您的 HOC 将函数作为道具传递,您可以在渲染中使用它,只要它不会再次导致重新渲染,否则将导致无限循环。

此外,最好记住直接在渲染中调用的函数,以避免一次又一次的计算

CodeSandbox 演示


推荐阅读