该组件以前没有使用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();
});