Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/react-native/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs 在HoC中调用React钩子_Reactjs_React Native - Fatal编程技术网

Reactjs 在HoC中调用React钩子

Reactjs 在HoC中调用React钩子,reactjs,react-native,Reactjs,React Native,我有一个HoC,它接受一组组件,并将它们封装在一个div中,这基本上使它们可以切换。代码在浏览器中运行良好,但jest测试失败,intellisense显示使用useEffect的警告 import React,{useEffect} from "react"; export const swiper = (components) => { const swiperHoc = props => { useEffect(()=>{console.log('HocLo

我有一个HoC,它接受一组组件,并将它们封装在一个div中,这基本上使它们可以切换。代码在浏览器中运行良好,但jest测试失败,intellisense显示使用useEffect的警告

import React,{useEffect} from "react";

export const swiper = (components) => {
  const swiperHoc = props => {
    useEffect(()=>{console.log('HocLogged')})
    return <div>{components}</div>;
  };
  return swiperHoc;
};
有没有更好的方法在HoC中调用hook?我怎样才能摆脱这个警告呢


由于钩子已经过时,钩子有两个主要约定,由其linter插件检查以确保遵守这些规则

1) 不能在条件内调用钩子。不是我的话,想想“你爱我”。这是因为React依赖于钩子调用的顺序

2) 您只能在自定义函数中以use word开头调用钩子(当然还有顶级组件)。这是一种让lint只在自定义钩子上运行的方法,另外还有一种让阅读代码的人理解在某个组件内部调用的函数使用某个钩子(状态等)的方法


在您的情况下,将函数重命名为useSwiperHoc,我也会将hoc本身重命名为useSwiper。

谢谢您的输入。我从你的回答中得到了一个命名线索,并让它发挥作用。但是,我做了2个更正,1)将组件名称替换为Pascal大小写(swiper到swiper,swiperHoc到swiper Hoc.2),这是我使用的jest
render()
而不是
render({component})
Invariant Violation: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
    1. You might have mismatching versions of React and the renderer (such as React DOM)
    2. You might be breaking the Rules of Hooks
    3. You might have more than one copy of React in the same app
    See https: / / fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.