在 HoC 中使用 React 钩子时的警告 [英] Warning when using react hooks in HoC

查看:34
本文介绍了在 HoC 中使用 React 钩子时的警告的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个高阶组件,它应该为我的组件添加一些额外的功能.但是,当我在这个组件中使用 react hooks 时,我收到以下 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 函数组件或自定义 React 中调用挂钩功能.(反应钩子/钩子规则)

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)

为什么我会收到此警告?在 HoC 中使用钩子被认为是不好的做法吗?

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)

代码沙盒:https://codesandbox.io/s/proud-tree-5kscc

推荐答案

转换

props => {
  React.useEffect(() => {
    // Do something here
  }, []);
  return <Component {...props} />;
};

在您的 HOC 内部到一个函数(react-hooks/rules-of-hooks 会抛出您在 HOC 返回的箭头函数中使用时显示的警告)

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆