在HoC中使用React钩子时发出警告 [英] Warning when using react hooks in HoC
问题描述
我创建了一个更高阶的组件,该组件应该为我的组件添加一些其他功能。但是,当我在该组件中使用react挂钩时,会收到以下eslint警告。
I've created a a higher order component that is supposed to add some additional functionality to my components. However, when I use react hooks in this component, I get the following eslint warning.
React Hook无法调用 React.useEffect在回调中。 React
Hook必须在React函数组件或自定义的React
Hook函数中调用。 (反应挂钩/挂钩规则)
React Hook "React.useEffect" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function. (react-hooks/rules-of-hooks)
为什么会收到此警告?
Why am I getting this warning? Is it considered bad practice to use hooks in a HoC?
最小示例:
const Hello = props => <p>Greetings {props.name}</p>;
const Wrapper = Component => props => {
React.useEffect(() => {
// Do something here
}, []);
return <Component {...props} />;
};
export default Wrapper(Hello)
codesandbox:
< a href = https://codesandbox.io/s/proud-tree-5kscc rel = noreferrer> https://codesandbox.io/s/proud-tree-5kscc
codesandbox: https://codesandbox.io/s/proud-tree-5kscc
推荐答案
转换
props => {
React.useEffect(() => {
// Do something here
}, []);
return <Component {...props} />;
};
将您的HOC放在函数内(react-hooks / rules-of-hooks会向您发出警告
inside your HOC to a function (react-hooks/rules-of-hooks is throwing that warning you showed when used in an arrow function returned by a HOC)
因此,将其更改为
const Wrapper = Component =>
function Comp(props) {
React.useEffect(() => {
console.log("useEffect");
}, []);
return <Component {...props} />;
};
并触发效果。
这篇关于在HoC中使用React钩子时发出警告的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!