错误消息:React Hook“useDispatch”是有条件调用的。在每个组件呈现中,必须以完全相同的顺序调用React Hook
几天来我一直在想如何修复这个问题,但是没有任何效果。当我不模拟任何东西的时候,这个组件可以工作,但是当我模拟调度的时候,它就给我这个错误。
以下是我的组件:
import { Stage } from "../Stage/Stage";
import { useDispatch, useSelector } from "react-redux";
import { useEffect } from "react";
import { retrieveStageList } from "../../modules/reducer";
import { Process } from "../Process/Process";
export function RenderProcess({
_useSelector = useSelector,
_useDispatch = useDispatch(), //this is where it breaks
_Process = Process,
}) {
const dispatch = _useDispatch();
const process = _useSelector((state) => state.renderProcess);
const stageList = _useSelector((state) => state.stageList);
useEffect(() => {
if (process.processId !== null)
dispatch(retrieveStageList(process.processId));
}, []);
return (
<>
<_Process process={process} />
{stageList?.map((stageInputs, processId) => {
return (
<div key={processId}>
<Stage stage={stageInputs} />
</div>
);
})}
</>
);
}
下面是我对这个组件的测试:
import { render } from "@testing-library/react";
import { RenderProcess } from "./RenderProcess";
test("should call dispatch once.", () => {
const _useSelector = (fn) =>
fn({
stageList: [],
renderProcess: { processId: "309624b6-9c96-4ba7-8f7e-78831614f685" },
});
const dispatch = jest.fn();
render(
<RenderProcess
_useSelector={_useSelector}
_useDispatch={() => dispatch}
_Process={() => {}}
/>
);
expect(dispatch).toHaveBeenCalledTimes(1);
});
如果能帮上忙就太好了。
1条答案
按热度按时间h43kikqp1#
在RenderProcess中传递的属性中找到了修复-在此
_useDispatch = useDispatch()
_useDispatch = useDispatch
个