无法在 HOC 中为功能组件使用钩子

Unable to use hook in HOC for functional component

使用 HOC 渲染功能组件即。这里的 SampleComponent 对我有用。

const SampleComponent: FC = () => {
  return (<div>Hello World</div>);
};

export default HOC({ component: SampleComponent });

HOC 是->

const HOC = ({ component: Component }) => {
  return (() => <Component/>);
}

但是我想有条件地渲染这个组件,就像这样-

<div> 
{!id ? ( <SomeOtherComponent prop1={'hello'} prop2={'world'} /> ) : ( <Component /> )}
</div>

这里的 id 是来自 graphql 查询钩子的响应,我再次无法在 HOC 函数中使用它。

对于初学者来说,hooks 应该是 HOC 的替代品。

但是,你绝对可以在一个函数组件的高阶组件中使用钩子。唯一需要确保的是,您在呈现的组件中使用钩子而不是函数。

例如,使用如下所示的钩子是不正确的,因为您不渲染 HOC 组件,而是像 const X = HOC(Component);

那样使用它
const HOC = ({ component: Component }) => { 
  const id = useQuery(query);
  return (() => <Component/>);
}

正确的做法是

const HOC = ({ component: Component }) => {
  return () => {
     const id = useQuery(query);
     return (<div> 
         {!id ? ( <SomeOtherComponent prop1={'hello'} prop2={'world'} /> ) : ( <Component /> )}
     </div>)
  }
}

Working sample demo

然而,当你像上面那样实现它时,你可能会收到 ESLINT 警告,因为 ESLINT 还不够智能,无法检测组件的使用方式。 您可以禁用此类情况的警告