[英]How to fix useDispatch REACT hook being called conditionally when mocking dispatch
Error Message: React Hook "useDispatch" is called conditionally.错误消息:有条件地调用 React Hook“useDispatch”。 React Hooks must be called in the exact same order in every component render
React Hooks 必须在每个组件渲染中以完全相同的顺序调用
I've been trying to figure out how to fix this for days, but nothing seeems to work.几天来我一直在想办法解决这个问题,但似乎没有任何效果。 The component works when I don't mock anything, but as soon as I mock dispatch it gives me this error.
当我不模拟任何东西时,该组件可以工作,但是一旦我模拟分派,它就会给我这个错误。
Here's my component:这是我的组件:
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>
);
})}
</>
);
}
Here's my test for this component:这是我对此组件的测试:
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);
});
Any help on this would be amazing.对此的任何帮助都将是惊人的。
Found the fix, in the properties being passed in RenderProcess- on this在 RenderProcess 中传递的属性中找到了修复 - 在此
_useDispatch = useDispatch()
_useDispatch = useDispatch()
_useDispatch = useDispatch
_useDispatch = useDispatch
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.