在HOC中使用useState / Hooks进行反应会导致错误“只能在函数组件的主体内部调用挂钩”

时间:2019-04-15 20:13:09

标签: javascript reactjs react-hooks

是否不允许在高阶组件内部使用钩子?当我尝试使用这种简单模式进行操作时,出现错误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;

2 个答案:

答案 0 :(得分:2)

我相信您应该使用HOC内的钩子:

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

答案 1 :(得分:1)

受拉斐尔·索扎(Rafael Souza)的回答启发,您可以使用以下方法使它更加干净:

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