不允许在高阶组件中使用钩子吗?当我尝试使用这种简单的模式执行此操作时,我得到错误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} />
}
}