gpt4 book ai didi

javascript - 在 HOC 中使用 useState/Hooks 使用react导致错误 "Hooks can only be called inside of the body of a function component"

转载 作者:行者123 更新时间:2023-12-05 00:30:02 25 4
gpt4 key购买 nike

不允许在高阶组件内使用钩子(Hook)吗?当我尝试使用这个简单的模式时,我得到了错误 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 内部的钩子(Hook):

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

关于javascript - 在 HOC 中使用 useState/Hooks 使用react导致错误 "Hooks can only be called inside of the body of a function component",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55696601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com