繁体   English   中英

在 HOC 中使用 useState/Hooks 导致错误“Hooks can only be called inside of a function component”

[英]React Using useState/Hooks In HOC Causes Error "Hooks can only be called inside of the body of a function component"

是否不允许在高阶组件内部使用钩子? 当我尝试使用这个简单的模式执行此操作时,我收到错误Invalid hook call. Hooks can only be called inside of the body of a function component. Invalid hook call. Hooks can only be called inside of the body of a function component.

// App.js
import React, { useState } from 'react';

const WithState = (Component) => {
  const [state, dispatch] = useState(0);
  return () => <Component state={state} dispatch={dispatch} />;
}

const Counter = ({ state }) => {
  return (
    <div style={{ textAlign: 'center', margin: '0 auto'}}>
      {state}
    </div>
  )
}

const CounterWithState = WithState(Counter);

const App = () => {
  return <CounterWithState />;
}

export default App;

我相信你应该使用 HOC 中的钩子:

const WithState = (Component) => {
  const WithStateComponent = () => {
    const [state, dispatch] = useState(0);
    return <Component state={state} dispatch={dispatch} />;
  }
  return WithStateComponent;
}

受 Rafael Souza 的回答启发,您可以通过以下方式使其更加清洁:

const WithState = (Component) => {
  return () => {
    const [state, dispatch] = useState(0);
    return <Component state={state} dispatch={dispatch} />
  }
}

暂无
暂无

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

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