簡體   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