React - 如何确定组件是否为无状态/功能?

mad*_*ox2 16 javascript reactjs

我有继承自React.Component以下的功能/无状态组件和组件:

const Component1 = () => (<span>Hello</span>)

class Component2 extends React.Component {
  render() {
    return (<span>Hello</span>)
  }
}
Run Code Online (Sandbox Code Playgroud)

如何确定组件是否为无状态?有官方的方法吗?

isStateless(Component1) // true
isStateless(Component2) // false
Run Code Online (Sandbox Code Playgroud)

Dor*_*man 15

你可以查看它的原型,例如:

function isStateless(Component) {
    return !Component.prototype.render;
}
Run Code Online (Sandbox Code Playgroud)

  • 组件可能没有原型 (2认同)

Est*_*ask 6

类组件本质上是有状态的,但是随着React钩子的引入,功能组件不再被称为无状态的,因为它们也可以是有状态的。

isReactComponentReact.Component从React 0.14开始就有特殊的属性。这允许确定组件是否为类组件。

function isFunctionalComponent(Component) {
  return (
    typeof Component === 'function' // can be various things
    && !(
      Component.prototype // native arrows don't have prototypes
      && Component.prototype.isReactComponent // special property
    )
  );
}

function isClassComponent(Component) {
  return !!(
    typeof Component === 'function'
    && Component.prototype
    && Component.prototype.isReactComponent
  );
}
Run Code Online (Sandbox Code Playgroud)

在React代码库中执行类似的检查。

由于组件可以是各种事物,如上下文ProviderConsumerisFunctionalComponent(Component)可能不等于!isClassComponent(Component)