简体   繁体   中英

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

Is it not allowed to use hooks inside of a Higher Order Component? When I try to do it with this simple pattern I'm getting the error 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;

I believe you should use the hooks inside the HOC:

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

Inspired by Rafael Souza's answer, you can make it even cleaner with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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