挂钩调用无效。钩子只能在函数组件的主体内部调用。这可能由于以下原因之一而发生

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons

我收到错误消息 Invalid hook call。钩子只能在函数组件的主体内部调用。我需要理解为什么我不能在项目中使用 React Hooks。这是我的 package.json 文件。

"@types/react": "16.8.6",
 "@types/react-dom": "16.8.2",
 "react": "16.8.4",
 "react-dom": "16.8.3"

以下是错误的快照。

以下是此项目中使用的示例组件。

import React, { useState } from 'react';

export default function ExampleComponent() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

这是我的index.tsx

const handleInitCompleted = (initializedServices: UuiContexts) => {
  Object.assign(svc, initializedServices);
};

const UuiEnhancedApp = withRouter(({ history }) => (
  <ContextProvider
    apiDefinition={getApi}
    loadAppContext={api => api.loadAppContext()} // tslint:disable-line
    onInitCompleted={handleInitCompleted}
    history={history}
  >
    <ExampleComponent />
    <Snackbar />
    <Modals />
  </ContextProvider>
));

const RoutedApp = () => (
  <Router>
    <UuiEnhancedApp />
  </Router>
);

const ReduxApp = () => (
  <Root>
    <RoutedApp />
  </Root>
);

ReactDOM.render(<ReduxApp />, document.getElementById('root') as HTMLElement);
serviceWorker.register();

这是我的 Root.tsx 文件

interface IRootChildren {
  children: JSX.Element;
}

const middlewares = [reduxThunk, multiClientMiddleware(clients, config)];
const store = createStore(reducers, composeWithDevTools(applyMiddleware(...middlewares)));

export default ({ children }: IRootChildren) => {
  return (
    <Provider store={ store }>
      { children }
    </Provider>
  );
};

这样做,

npm install react@next react-dom@next

而Context Provider是一个HOC(高阶组件), 您正在将示例组件传递给它。 Hooks 在 HOC 中给出错误