React检测到MyComponent调用的Hooks顺序发生了变化

问题描述

该组件以前没有使用useRef钩子,我添加了一个ref来处理一些调整大小的更改,等等。起初一切都很好,测试通过了,不知道我更改了什么,现在它相信状态了挂钩渲染之间的更改。

以下是声明钩子的唯一地方,我应该包括设置状态的地方吗? (在useLayoutEffect中设置,然后在onScroll处理程序中设置)

错误:

Should have a queue. This is likely a bug in React. Please file an issue.

控制台消息:

 React has detected a change in the order of Hooks called by MyComponent. This will lead to bugs and errors if not fixed.
    
       Previous render            Next render
       ------------------------------------------------------
    1. useRef                     useState
       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
      66 |     const refContainer = useRef<HTMLUListElement>();
    > 67 |     const [ state1,setState1 ] = React.useState('none');
         |                                         ^
      68 |     const [ state2,setState2 ] = React.useState<boolean[]>(new Array(React.Children.count(children)).fill(false));

组件:

const myComponent = (props: PropType): JSX.Element => {
    const refContainer = useRef<HTMLUListElement>();
    const [ state1,setState1 ] = React.useState('none'); // 
    const [ state2,setState2 ] = React.useState<boolean[]>(new Array(React.Children.count(children)).fill(false));
...

}

测试:

    it('scroll',() => {
        const ref = jest.spyOn(React,'useRef').mockReturnValueOnce({ current: { scrollLeft: 26,offsetWidth: 24,scrollWidth: 50 } });
        myComponent.find('.x').simulate('scroll',ref);
        expect(myComponent.find('.x').hasClass('y')).toBeTruthy();
        expect(myComponent.find('.x').hasClass('y')).toBeFalsy();
    });

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...